c ++ beginner:对象没有正确执行的函数调用

时间:2014-08-02 01:38:55

标签: c++ recursion function-calls

我无法弄清楚为什么代码没有正常执行。当我使用函数'加法器'在类的内部,如果它只是作为加法器(3,1)在main中运行并在类之外定义,则它不会返回它将具有的总和。

class Adder{
public:
Adder( int a, int b ) // constructor
{a=myValueofA;
    b=myValueofB;
};

int getA() const{
    return myValueofA;
};

int getB() const{
    return myValueofB;
};

和递归加法函数

int adder(int x, int y)const
{
    if(x==0)
        return y;
    else if(y==0)
        return x;
    else
        return adder(--x,++y);
}

后跟将在main中调用的函数。

  int RecursiveAPlusB() const{


    return adder(myValueofA, myValueofB);

私有成员变量:

int myValueofA;
int myValueofB;

现在进入main()

{
Adder ten( 3, 4 );
// this call should produce 7 but yields 0;
cout  << ten.RecursiveAPlusB() << endl;
return 0;}

我用来访问变量的方法有趣且低效(并且不能工作)。有什么建议? 另请注意,main中的驱动程序无法更改。  (作业要求。)

1 个答案:

答案 0 :(得分:3)

你的构造函数是向后的。代码:

Adder( int a, int b ) // constructor
{a=myValueofA;
    b=myValueofB;
};

myValueofA(尚未定义)的值放入变量a而不设置myValueofA,同样适用于myValueofB和{{1 }}。你的意思是:

b

或者,甚至更好:

Adder(int a, int b) {
    myValueofA = a;
    myValueofB = b;
}  // Note that no semicolon is needed after a function definition