【发布时间】:2021-10-19 05:34:34
【问题描述】:
我目前正在学习如何在 C++ 中进行运算符重载,我在网上找到了一些在下面运行时有效的代码。
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0) {
real = r;
imag = i;
}
// This is automatically called when '+' is used with
// between two Complex objects
Complex operator+(Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};
int main() {
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call to "operator+"
c3.print();
}
但是,当我尝试类似的结构时,我收到以下错误:未找到默认构造函数和
class Chicken {
private:
int i;
int k;
int s;
int total = 0;
public:
Chicken(int index, int kentucky, int sign) {
i = index;
k = kentucky;
s = sign;
}
Chicken operator+(Chicken obj) {
Chicken Chicky;
Chicky.total = i + obj.i;
return Chicky;
}
};
int main() {
Chicken P(1, 2, 3);
Chicken U(2, 2, 2);
Chicken W = P + U;
cout << W;
}
【问题讨论】: