这是一段代码,重载了<<运营商:
#include <iostream>
using namespace std;
namespace MyNamespace
{
template <typename T>
class MyClass
{
const int a = 5;
template <typename U>
friend std::ostream& operator<<(std::ostream &os, const MyClass<U>& obj);
};
}
template <typename U>
std::ostream& operator<<(std::ostream &os, const MyNamespace::MyClass<U>& obj)
{
return cout << obj.a;
}
int main()
{
MyNamespace::MyClass<int> foo;
cout << foo;
// your code goes here
return 0;
}
当我编译时,我得到'运算符&lt;&lt;'的模糊重载。
我不明白为什么......
答案 0 :(得分:2)
你有一个
std::ostream& MyNamespace::operator<<(std::ostream &os, const MyClass<U>& obj);
在您的班级中声明为friend
和
std::ostream& operator<<(std::ostream &os, const MyNamespace::MyClass<U>& obj)
在全局命名空间中。要告诉C ++第二个(全局的)是您的朋友函数而不是命名空间中的函数,请在名称后附加::
:
std::ostream& ::operator<<(std::ostream &os, const MyClass<U>& obj);
或者更好的是,将函数移动到您自己的命名空间。