【发布时间】:2021-01-28 07:23:39
【问题描述】:
我正在从一本书中学习 C++,我发现引用和运算符重载非常困难。在研究运算符重载时,我不明白为什么如果没有一个以整数作为参数的构造函数,这个程序就无法工作。
#include <iostream>
using namespace std;
class counter {
public:
counter();
counter(int value);
~counter();
int getValue() const { return itsValue; }
int setValue(int value) { itsValue = value; }
counter operator+(const counter&);
private:
int itsValue;
};
counter::counter() :
itsValue(0)
{}
counter::counter(int value) :
itsValue(value)
{}
counter counter::operator+(const counter& rhs) {
return itsValue + rhs.getValue();
}
int main()
{
std::cout << "Hello World!\n";
}
我不明白为什么程序在没有这些行的情况下无法运行:
counter(int value);
与
counter::counter(int value) :
itsValue(value)
{}
【问题讨论】:
-
为什么您认为没有这些行程序将无法运行? (你是对的,它没有,但问题应该显示完整的错误消息)
-
您还缺少构造函数定义