|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
代码如下:
- #include<iostream>
- using namespace std;
- template <class Value>
- class Complex
- {
- private:
- Value real;
- Value image;
- public:
- Complex(Value xx = 0, Value yy = 0);
- template<class T>
- friend Complex operator + (const Complex<T> &a, const Complex<T> &b);
- template<class T>
- friend Complex operator - (const Complex<T> &a, const Complex<T> &b);
- void Print();
- };
- int main()
- {
- double a, b, c, d;
- cout << "请输入第一个复数的实部虚部:" << endl;
- cout << "虚部:";
- cin >> a;
- cout << "实部:";
- cin >> b;
- cout << "请输入第二个复数的实部虚部:" << endl;
- cout << "虚部:";
- cin >> c;
- cout << "实部:";
- cin >> d;
- Complex<double> aa(a, b), bb(c, d),cc;
- aa + bb;
- cout << "两复数相加的值为:";
- cc.Print();
- cout << "两复数相减的值为:";
- aa - bb;
- cc.Print();
- system("Pause");
- return 0;
- }
- template <class Value>
- Complex<Value>::Complex(Value cc, Value dd)
- {
- real = cc;
- image = dd;
- }
- template<class Value>
- void Complex<Value>::Print()
- {
- cout << real;
- if (image != 0)
- {
- if (image > 0)
- cout << " + ";
- cout << image << "i ";
- }
- cout << endl;
- }
- template<class T>
- Complex<T> operator + (Complex<T> &a, Complex<T> &b)
- {
- Complex<T> copy;
- copy.real = a.real + b.real;
- copy.image = a.image + b.image;
- return copy;
- }
- template<class T>
- Complex<T> operator - (Complex<T> &a, Complex<T> &b)
- {
- Complex<T> copy;
- copy.real = a.real - b.real;
- copy.image = a.image - b.image;
- return copy;
- }
复制代码
本帖最后由 Croper 于 2019-5-16 18:00 编辑
首先,加不加const是两个函数,你的友元声明里有const,后面的定义里却没有const,这是第一个问题
第二,友元声明里你的返回值没有模板参数,按照定义,会自动套用原来的模板参数,于是,你的友元声明其实是这样的:
- template <typename Value>
- template <typename T>
- Complex<Value> operator+(const Complex<T>&,const Complex<T>&);
复制代码
然而,C++并不允许重载仅仅只有返回值类型不同的函数。因此,你这个友元声明是错误的。
改正以上两点已经正确可以运行了
这里提一下,你这样重载的话其实建立的并不是一一对应的友元关系,而是把所有类型的operator+都声明为了友元,换句话说,operator+<int>也可以访问Complex<double>的私有数据成员。
所以如果追求一一对应的话,那么需要把函数声明,友元声明和函数定义分开写。
一对多的友元声明我就不给代码了,你把前两点改了就行,
这是一一对应的友元声明的代码: - #include<iostream>
- using namespace std;
- template <typename T> class Complex; //首先声明类
- template <typename T> Complex<T> operator+(const Complex<T>&, const Complex<T>&); //函数声明
- template <typename T> Complex<T> operator-(const Complex<T>&, const Complex<T>&);
- template <class T>
- class Complex
- {
- friend Complex operator+<T>(const Complex&, const Complex&); //友元声明
- friend Complex operator-<T>(const Complex&, const Complex&);
-
- ...
- };
- ...
- template<class T>
- Complex<T> operator + (const Complex<T> &a, const Complex<T> &b) //函数定义
- {
- Complex<T> copy;
- copy.real = a.real + b.real;
- copy.image = a.image + b.image;
- return copy;
- }
- template<class T>
- Complex<T> operator - (const Complex<T> &a, const Complex<T> &b)
- {
- Complex<T> copy;
- copy.real = a.real - b.real;
- copy.image = a.image - b.image;
- return copy;
- }
复制代码
|
|