|
发表于 2023-10-18 16:04:36
|
显示全部楼层
问题出在友元函数的声明和定义上。友元函数的声明应该放在类的内部,而定义应该放在类的外部。在你的代码中,友元函数的声明放在了类的内部,这导致了访问私有成员变量时的错误。
要修复这个问题,你需要将友元函数的声明移动到类的外部,并在函数声明中指定参数为常引用。这样,友元函数就可以正确地访问私有成员变量了。
以下是修复后的代码:
- #include <iostream>
- using namespace std;
- class Complex
- {
- public:
- Complex() {
- real = 0;
- imag = 0;
- }
- Complex(double r, double i) {
- real = r;
- imag = i;
- }
- friend Complex operator+(const Complex &c, const Complex &d); // 将友元函数的声明移动到类的外部,并指定参数为常引用
- void print() {
- cout << "(" << real << "," << imag << "i)\n";
- }
- private:
- double real;
- double imag;
- };
- Complex operator+(const Complex &c, const Complex &d) // 友元函数的定义放在类的外部,并指定参数为常引用
- {
- return Complex(c.real + d.real, c.imag + d.imag);
- }
- int main()
- {
- Complex c1(3, 4), c2(5, -10), c3;
- c3 = c1 + c2;
- cout << "c1 = ";
- c1.print();
- cout << "c2 = ";
- c2.print();
- cout << "c1 + c2 = ";
- c3.print();
- return 0;
- }
复制代码
修复后的代码应该可以正确编译和运行,输出结果为:
- c1 = (3,4i)
- c2 = (5,-10i)
- c1 + c2 = (8,-6i)
复制代码 |
|