class C { friend C operator+ (const C&, const C&); /* …… */ }; C C::operator+ (const C& c1, const C& c2) { /* …… */ }
时间: 2024-03-27 19:41:28 浏览: 20
这段代码中定义了一个名为 `C` 的类,并定义了一个名为 `operator+` 的友元函数,该函数接受两个 `C` 类型的参数,并返回一个 `C` 类型的对象。
在类外定义 `operator+` 函数时需要指明该函数属于哪个类,因此要在函数名前加上类名 `C::`。另外,由于 `operator+` 函数是一个友元函数,因此需要在类定义中声明一下该函数。
下面是完整代码示例:
```cpp
class C {
friend C operator+(const C&, const C&);
public:
// ...
};
C operator+(const C& c1, const C& c2) {
// ...
}
```
注意,在定义友元函数时,需要在函数名前加上 `friend` 关键字,但在类外定义时则不需要。另外,友元函数可以访问该类的私有成员,但不属于该类。
相关问题
class C { friend C operator+ (const C&, const C&); /* …… / }; C C::operator+ (const C& c1, const C& c2) { / …… */ }的错误
这段代码有两处错误:
1. `operator+` 函数是一个友元函数,不属于类 `C`,因此不能使用类作用域运算符 `::` 来定义该函数。应该在类外定义该函数。
2. 在类中声明 `operator+` 函数时,应该声明函数原型,而不是定义函数。因此应该将函数体中的代码移到函数原型之后的花括号中去。
下面是正确的代码示例:
```cpp
class C {
friend C operator+(const C&, const C&);
};
C operator+(const C& c1, const C& c2) {
C result;
// 对 c1 和 c2 进行加法运算,并将结果存储在 result 中
return result;
}
```
这样就可以在类外定义 `operator+` 函数,并在类中声明该函数的友元关系了。注意,由于 `operator+` 是一个友元函数,因此不需要将 `C` 类型的对象作为第一个参数传递给该函数。
class Complex{ double real, imag; public: Complex(double r=0, double i=0): real(r), imag(i){ } friend istream& operator>>(istream& in, Complex& c); //已实现 friend ostream& operator<<(ostream& out, const Complex& c);//已实现 friend Complex operator+(const Complex& c1, const Complex& c2); friend Complex operator-(const Complex& c1, const Complex& c2); Complex& operator+=(const Complex& c); Complex& operator-=(const Complex& c); };#include <iostream> using namespace std; int main() { Complex c1, c2; cin >> c1 >> c2; cout << c1 + c2 << endl; cout << c1 - c2 << endl; c1 += c2; cout << c1 << endl; c1 -= c2; cout << c1 << endl; return 0; } /* 请在这里填写答案,类的详细定义已由系统给出,并重载了输入输出运算符,你只需要写出需要重载的算术运算符函数即可 */
重载的算术运算符函数如下所示:
```c++
Complex operator+(const Complex& c1, const Complex& c2){
return Complex(c1.real+c2.real, c1.imag+c2.imag);
}
Complex operator-(const Complex& c1, const Complex& c2){
return Complex(c1.real-c2.real, c1.imag-c2.imag);
}
Complex& Complex::operator+=(const Complex& c){
real += c.real;
imag += c.imag;
return *this;
}
Complex& Complex::operator-=(const Complex& c){
real -= c.real;
imag -= c.imag;
return *this;
}
```
其中,`operator+` 重载了加法运算符,返回两个复数相加的结果;`operator-` 重载了减法运算符,返回两个复数相减的结果;`operator+=` 重载了复合赋值加法运算符,将一个复数加上另一个复数并返回结果;`operator-=` 重载了复合赋值减法运算符,将一个复数减去另一个复数并返回结果。