#include <iostream>
using namespace std;
template<typename T>
class Complex
{
public:
Complex(T a ,T b);
void printCom();
Complex operator+(const Complex &c);//成员函数实现+运算符重载
protected:
private:
//声明位置无关
friend ostream& operator<< <T>(ostream &out,const Complex<T> &c);
friend Complex MySub(const Complex &c1,const Complex &c2)
{
Complex tmp(c1.a-c2.a,c1.b-c2.b);
return tmp;
}
int a;
int b;
};
//运算符重载的正确写法 重载<< >>只能使用友元函数,其他运算符重载都要写成成员函数,不要滥用友元
/*
template<typename T>
ostream& operator<<(ostream &out,const Complex<T> &c)
{
out<<"a:"<<c.a<<"b:"<<c.b;
return out;
}
*/
template<typename T>
Complex<T>::Complex(T a ,T b)
{
this->a = a;
this->b = b;
}
template<typename T>
void Complex<T>::printCom()
{
cout<<"a:"<<a<<"b:"<<b<<endl;
}
template<typename T>
Complex<T> Complex<T>::operator+(const Complex<T> &c)
{
Complex<T> tmp(this->a + c.a,this->b+c.b);//这个地方<T>加不加 都可以
return tmp;
}
/*错误 1 error LNK2019: 无法解析的外部符号 "
class std::basic_ostream<char,struct std::char_traits<char> >
& __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,
class Complex<int> const &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABV?$Complex@H@@@Z),
该符号在函数 _main 中被引用 E:\C++\project\数值\数值\复数类--所有函数都写在类的外部.obj 数值
*/
//原因:模板是两次编译生成的 第一次编译生成的函数头 和第二次编译生成的函数头 不一样导致的 所以找不到外部符号
//如何解决 在类中的函数声明处 “<<”的=后面加上<T>
//友元函数实现<<重载
template<typename T>
ostream& operator<<(ostream &out,const Complex<T> &c)
{
out<<"a:"<<c.a<<"b:"<<c.b;
return out;
}
int main()
{
//需要把模板类具体化后才能进行定义对象 因为c++编译器要分配内存
Complex<int> c1(1,2);
Complex<int> c2(2,3);
Complex<int> c3 = c1 + c2;
cout<<c3<<endl;
system("pause");
return 0;
}
滥用友元产生的第一个问题
最新推荐文章于 2018-04-01 20:48:23 发布