【问题标题】:c++ beginner: function call on object not executing properlyc ++初学者:对对象的函数调用未正确执行
【发布时间】:2014-08-02 01:38:55
【问题描述】:

我无法弄清楚为什么代码没有正确执行。当我在类内部使用函数“adder”时,它不会返回如果它只是在 main 中作为 adder(3,1) 运行并在类外部定义的总和。

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 中的驱动程序。 (作业要求。)

【问题讨论】:

  • 那么我们是否应该假设class adder 是一个错误,因为在其他任何地方Adder 都是类的名称?如果是,请请,发布真实代码。

标签: c++ recursion function-calls


【解决方案1】:

你的构造函数是倒退的。代码:

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

将myValueofA 的值(尚未定义)放入变量a 而不设置myValueofA,同样适用于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) { }

【讨论】:

    猜你喜欢
    • 2012-04-03
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    相关资源
    最近更新 更多