我不明白为什么代码没有正确执行。当我在类内部使用函数“adder”时,它不会返回如果它作为 adder(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);
私有(private)成员变量:
int myValueofA;
int myValueofB;
现在进入 main()
{
Adder ten( 3, 4 );
// this call should produce 7 but yields 0;
cout << ten.RecursiveAPlusB() << endl;
return 0;}
我用来访问变量的方法既有趣又低效(而且不起作用)。有什么建议么? 另请注意,main 中的驱动程序无法更改。 (作业要求。)
最佳答案
你的构造函数是倒退的。代码:
Adder( int a, int b ) // constructor
{a=myValueofA;
b=myValueofB;
};
在不设置 myValueofA
的情况下将 myValueofA
的值(尚未定义)放入变量 a
中,同样适用于 myValueofB
和 b
。你要写的是:
Adder(int a, int b) {
myValueofA = a;
myValueofB = b;
} // Note that no semicolon is needed after a function definition
或者,甚至更好:
Adder(int a, int b) : myValueofA(a), myValueofB(b) { }
关于C++ 初学者 : function call on object not executing properly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25090848/