C++ 类模板二(类模版与友元函数)
生活随笔
收集整理的這篇文章主要介紹了
C++ 类模板二(类模版与友元函数)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
http://www.cnblogs.com/zhanggaofeng/p/5661829.html
//類模版與友元函數(shù)
#include<iostream>
using namespace std;template<typename T>
class Complex{
public:Complex(T a,T b);void Print() const//const修飾的是this指針{cout << this->Real << ":" <<this->Image<< endl;}/*強(qiáng)調(diào):在類模板里實(shí)現(xiàn)友元函數(shù) 不可以寫在類的外部,只能在類的內(nèi)部實(shí)現(xiàn),否則編譯器報(bào)錯(cuò)本質(zhì)原因是類模板編譯了2次,導(dǎo)致對(duì)友元函數(shù)也編譯了2次 所以c++編譯器不認(rèn)可寫在類模板外面的友元函數(shù)對(duì)于普通類則沒(méi)有這個(gè)問(wèn)題*///友元函數(shù)friend Complex operator+(Complex &c1, Complex &c2){Complex tempc(c1.Real + c2.Real, c1.Image + c2.Image);return tempc;//匿名對(duì)象}//成員函數(shù)---成員函數(shù)跟友元函數(shù)不同,可以在類外面實(shí)現(xiàn)Complex operator-(Complex &c2);
private:T Real, Image;
};template<typename T>
Complex<T>::Complex(T a, T b){this->Real = a;this->Image = b;
}template<typename T>
Complex<T> Complex<T>::operator-(Complex<T> &c2){Complex tempc(this->Real - c2.Real, this->Image - c2.Image);return tempc;//匿名對(duì)象
}void ProtectA(){Complex<int> c1(3,4);//c1.Print();Complex<int> c2(5, 7);//運(yùn)算符重載 + 友元函數(shù)實(shí)現(xiàn)Complex<int> c3 = c1 + c2;c3.Print();/*首先承認(rèn)運(yùn)算符重載是一個(gè)函數(shù),寫出函數(shù)名operator+然后根據(jù)操作數(shù),寫出參數(shù)列表operator+(Complex<int> &c1,Complex<int> &c2)最后根據(jù)接收對(duì)象決定返回值,實(shí)現(xiàn)函數(shù)Complex<int> operator+(Complex<int> &c1,Complex<int> &c2)在類的內(nèi)部可以省略參數(shù)列表,因?yàn)轭惖穆暶鞑环峙鋬?nèi)存,不需要確定類的大小*/Complex<int> c4 = c2 - c1;/*首先承認(rèn)運(yùn)算符重載是一個(gè)類內(nèi)部函數(shù),寫出函數(shù)名operator-然后根據(jù)操作數(shù),寫出參數(shù)列表c1.operator-(Complex<int> &c2);最后根據(jù)接收對(duì)象決定返回值,實(shí)現(xiàn)函數(shù)Complex<int> c1.operator-(Complex<int> &c2);在類的內(nèi)部可以省略參數(shù)列表,因?yàn)轭惖穆暶鞑环峙鋬?nèi)存,不需要確定類的大小 參數(shù)列表就是<T>*/c4.Print();}void main(){ProtectA();system("pause");
}
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)
總結(jié)
以上是生活随笔為你收集整理的C++ 类模板二(类模版与友元函数)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【C/C++】关键字static
- 下一篇: 基于Visual C++2013拆解世界