C++ 初学者 : function call on object not executing properly

标签 c++ recursion function-calls

我不明白为什么代码没有正确执行。当我在类内部使用函数“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 中,同样适用于 myValueofBb。你要写的是:

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/

相关文章:

java - 列表作为Java中的输出参数

c++ - 使用 C++ 以最快的方式在超大文本文件 (10 GB) 中搜索多个单词

list - 如何递归地请求输入并返回列表

c++ - 递归模板函数内的无限循环

python - 内存无法按预期工作

python - 如何在 Python 中的函数调用之间维护列表和字典?

c - (C) 有人可以向我解释为什么代码会返回它的作用吗?

c++ - 在 boost::ublas 中禁用警告日志

c++ - 非成员函数如何改进封装

html - C++:如何从网站 HTML 中提取多个 URL 到一个 vector 中?