【问题标题】:Function don't work in the class (c++)函数在类中不起作用(c++)
【发布时间】:2018-05-02 17:10:32
【问题描述】:

刚开始学习OOP,我写了简单的程序,但是函数int sum()有错误,你能写出问题的决定吗?并解释错误。

class Int 
{
private:
   int num;
public
Int()
{
    num = 0;
}
Int(int n)
{
    num = n;
}
 int getValue()
{
    return num;
}
 int sum(const Int& n)
{
    return num+ n.getValue();
}
void main()
{
short a, b;
cout <<  "Enter 2 numbers:";
cin >> a >> b;
Int A(a), B(b), res;
cout << A.getValue() << " + " << B.getValue() << " = " << A.sum(B) <<"\n\n";
}

【问题讨论】:

  • 您的部分源代码在发布时似乎丢失了。请编辑您的帖子以包含整个源代码。
  • 欢迎来到 Stack Overflow!通常,您应该包含您收到的详细错误消息。在这种情况下,您的函数 sum(const Int&amp; n) 的主体似乎丢失了
  • 如果那是你的真实代码,你应该在构建时遇到 很多 错误。
  • 对不起,没看到
  • 好的,您的编辑让它变得更好了,但您似乎仍然只是在没有太多实际知识的情况下涉足。 Int 类在哪里结束?也许你应该退后几步,get a couple of good books 重新开始?

标签: c++ oop


【解决方案1】:

以下是我的尝试。存在一些格式问题,但最棘手的问题是 getValue() 是一个 const 函数。

class Int {
 private:
  int num;

 public:
  Int() { num = 0; }
  Int(int n) { num = n; }

  // getValue is a const function as it does not alter object 'n'.
  int getValue() const { return num; }
  int sum(const Int& n) { 
    int ret = num + n.getValue(); 
    return ret;
  }
};

int main() {
    int a, b;
    std::cout << "Enter 2 numbers:";
    std::cin >> a >> b;
    Int A(a), B(b), res;
    std::cout << A.getValue() << " + " << B.getValue() << " = " << A.sum(B) << "\n\n";
}

【讨论】:

  • 非常感谢。没想到这么简单
【解决方案2】:

你不能像这样在另一个函数中声明一个函数。你在 sum() 中有 main()。

【讨论】:

  • 您能否通过单击左侧的向上箭头将我的回复标记为答案?
猜你喜欢
  • 2017-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多