滥用友元产生的第一个问题

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值