我有一个类使用嵌套类,并且想要使用嵌套类operator<<
在上层类中定义operator<<
。这里是我的代码看起来像:重载运算符<<:不能将左值绑定到'std :: basic_ostream <char> &&'
#include <memory>
#include <iostream>
template<typename T>
struct classA {
struct classB
{
template<typename U>
friend inline std::ostream& operator<< (std::ostream &out,
const typename classA<U>::classB &b);
};
classB root;
template<typename U>
friend std::ostream& operator<< (std::ostream &out,
const classA<U> &tree);
};
template<typename T>
inline std::ostream& operator<< (std::ostream &out,
const classA<T> &tree)
{
out << tree.root;
return out;
}
template<typename T>
inline std::ostream& operator<< (std::ostream &out,
const typename classA<T>::classB &b)
{
return out;
}
int main()
{
classA<int> a;
std::cout << a;
}
当没有为C++ 11的支持编制,运营商< <为内部类的定义似乎不被编译器发现:
与STD编译时so.hpp:24:7: error: no match for ‘operator<<’ in ‘out << tree.classA<int>::root’ so.hpp:24:7: note: candidates are: ...
随着GCC 4.6和4.7 =的C++ 0x:
so.hpp:21:3: error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’ In file included from /usr/include/c++/4.7/iostream:40:0, from so.hpp:2: /usr/include/c++/4.7/ostream:600:5: error: initializing argument 1 of ‘std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = classA<int>::classB]’
有人能告诉我为什么这段代码是不合法的,什么是做我想做的最好的方法?
感谢您提供解决方法。 – Antoine
我看到它像一个*更好的设计*而不是*解决方法*。它有缺点(你不能把模板类中声明的朋友函数的地址),但在所有其他帐户上,它更适合提供免费函数操作符... –
这是[Making New Friends](https ://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Making_New_Friends)成语,所以不是真正的解决方法。 – TBBle