問題描述
我遇到了重載 <<
流運算符的問題,但我沒有找到解決方案:
I have a problem to overload the <<
stream operator and I don't find the solution :
template<class T, unsigned int TN>
class NVector
{
inline friend std::ostream& operator<< (
std::ostream &lhs, const NVector<T, TN> &rhs);
};
template<class T, unsigned int TN>
inline std::ostream& NVector<T, TN>::operator<<(
std::ostream &lhs, const NVector<T, TN> &rhs)
{
/* SOMETHING */
return lhs;
};
它產生以下錯誤消息:
警告:朋友聲明‘std::ostream&operator<<(std::ostream&, const NVector&)' 聲明了一個非模板函數[-Wnon-template-friend]
warning : friend declaration ‘std::ostream& operator<<(std::ostream&, const NVector&)’ declares a non-template function [-Wnon-template-friend]
錯誤:'std::ostream&NVector::operator<<(std::ostream&, const NVector&)' 必須只取一個參數
error: ‘std::ostream& NVector::operator<<(std::ostream&, const NVector&)’ must take exactly one argument
如何解決這個問題?
非常感謝.
推薦答案
在你的代碼中有兩個不同的問題,第一個是 friend
聲明(正如警告明確說的,也許不是這樣清晰易懂)將單個非模板化函數聲明為友元.也就是說,當您實例化模板 NVector
時,它聲明了一個非模板化函數 std::ostream&operator<<(std::ostream&,NVector
作為朋友.請注意,這與聲明您作為朋友提供的模板函數不同.
There are two different issues in your code, the first is that the friend
declaration (as the warning clearly says, maybe not so clear to understand) declares a single non-templated function as a friend. That is, when you instantiate the template NVector<int,5>
it declares a non-templated function std::ostream& operator<<(std::ostream&,NVector<int,5>)
as a friend. Note that this is different from declaring the template function that you provided as a friend.
我建議您在類定義中定義友元函數.您可以在此答案中閱讀更多相關信息.
I would recommend that you define the friend function inside the class definition. You can read more on this in this answer.
template <typename T, unsigned int TN>
class NVector {
friend std::ostream& operator<<( std::ostream& o, NVector const & v ) {
// code goes here
return o;
}
};
或者,您可以選擇其他選項:
Alternatively you can opt for other options:
- 將
operator<<
模板聲明為朋友(將授予對模板的任何和所有實例的訪問權限), - 將該模板的特定實例聲明為朋友(編寫起來更麻煩)或
- 完全避免友誼提供公共
print(std::ostream&)
成員函數并從非友元模板operator<<
調用它.我仍然會選擇與非模板函數交朋友,并在模板化類中提供定義.
- declare the
operator<<
template as a friend (will grant access to any and all instantiations of the template), - declare a particular instantiation of that template as a friend (more cumbersome to write) or
- avoid friendship altogether providing a public
print( std::ostream& )
member function and calling it from a non-friend templatedoperator<<
. I would still opt to befriend the non-template function an provide the definition inside the templated class.
第二個問題是,當您想在左側參數的類之外定義一個運算符時,該運算符是一個自由函數(未綁定到類),因此它應該不合格:
The second issue is that when you want to define an operator outside of the class of the left hand side argument, the operator is a free function (not bound to a class) and thus it should not be qualified:
template<class T, unsigned int TN>
inline std::ostream& operator<<(std::ostream &lhs, const NVector<T, TN> &rhs)
{
/* SOMETHING */
return lhs;
};
這篇關于C++:友元聲明‘聲明一個非模板函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!