C++ 类模板中友元函数问题
生活随笔
收集整理的這篇文章主要介紹了
C++ 类模板中友元函数问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#pragma once
#include<iostream>
template<typename T>
class TestFriendTemplate
{
public://模板類的友元函數的實現放在類外時,需加個<T>friend std::ostream& operator< <T> (std::ostream& out, const TestFriendTemplate<T>& ftemp);friend void TestFunc<T>(const TestFriendTemplate<T>& tmp);//模板以類的友元函數的實現在類內時,一切正常,不需要加<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; //報錯,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;
}//實現寫在這里可以,如果移動到一個cpp文件中,就編譯不過了,這也是模板的一個典型問題(當聲明和實現分別在頭文件和CPP中時)
template<typename T>
void TestFunc(const TestFriendTemplate<T>& tmp) {std::cout << "TestFunc:" << std::endl;
}
總結
以上是生活随笔為你收集整理的C++ 类模板中友元函数问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++友元与输出运算符重载
- 下一篇: C++类模板特化全总结