C++ 类模板中友元函数问题
生活随笔
收集整理的這篇文章主要介紹了
C++ 类模板中友元函数问题
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
#pragma once
#include<iostream>
template<typename T>
class TestFriendTemplate
{
public://模板類的友元函數(shù)的實(shí)現(xiàn)放在類外時(shí),需加個(gè)<T>friend std::ostream& operator< <T> (std::ostream& out, const TestFriendTemplate<T>& ftemp);friend void TestFunc<T>(const TestFriendTemplate<T>& tmp);//模板以類的友元函數(shù)的實(shí)現(xiàn)在類內(nèi)時(shí),一切正常,不需要加<T>friend std::ostream& operator<< (std::ostream& out, const TestFriendTemplate<T>& ftemp) {out << "TestFriendTemplate.operator<<:" << ftemp.x << ", " << ftemp.y;return out;}static void TestFriendTemp() {printf("TestFriendTemplate\n");std::ostream& out = std::cout; //正確//std::ostream out = std::cout; //報(bào)錯(cuò),basic_ostream(const basic_ostream&) = delete,禁止copy了}private:int x = 0;int y = 1;
};template<typename T>
std::ostream& operator<(std::ostream& out, const TestFriendTemplate<T>& ftemp)
{out << "TestFriendTemplate.operator<:" << ftemp.x << ", " << ftemp.y;return out;
}//實(shí)現(xiàn)寫在這里可以,如果移動(dòng)到一個(gè)cpp文件中,就編譯不過了,這也是模板的一個(gè)典型問題(當(dāng)聲明和實(shí)現(xiàn)分別在頭文件和CPP中時(shí))
template<typename T>
void TestFunc(const TestFriendTemplate<T>& tmp) {std::cout << "TestFunc:" << std::endl;
}
總結(jié)
以上是生活随笔為你收集整理的C++ 类模板中友元函数问题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++友元与输出运算符重载
- 下一篇: C++类模板特化全总结