感谢 Sam Varshavchik 的提示(在上面的评论中),我已经能够想出第一个版本的正确版本:
#include <iostream>
#include <string>
#include <sstream>
namespace Foo {
class Bar {
public:
std::string str;
friend std::istream& operator >>(std::istream& in, Bar& t);
};
std::istream& operator >>(std::istream& in, Bar& t);
}
std::istream& Foo::operator >>(std::istream& in, Foo::Bar& t) {
in >> t.str;
return in;
}
using namespace std;
int main() {
Foo::Bar foo;
stringstream("foo") >> foo;
cout << foo.str << endl;
return 0;
}
关键是确保 operator>> 函数在同一范围内声明和定义。我仍然希望能够在命名空间大括号之外定义函数,因此我必须在命名空间内添加一个声明,以便编译器知道命名空间中应该存在该函数。保持函数定义独立使我可以将代码分成三个文件:main.cpp、foo.hpp 和 foo.cpp:
// main.cpp
#include <iostream>
#include <string>
#include <sstream>
#include "foo.hpp"
using namespace std;
int main() {
Foo::Bar foo;
stringstream("foo") >> foo;
cout << foo.str << endl;
return 0;
}
// foo.hpp
#ifndef FOO_HPP
#define FOO_HPP
#include <string>
#include <iostream>
namespace Foo {
class Bar {
public:
std::string str;
friend std::istream& operator >>(std::istream& in, Bar& t);
};
std::istream& operator >>(std::istream& in, Bar& t);
}
#endif
// foo.cpp
#include "foo.hpp"
std::istream& Foo::operator >>(std::istream& in, Foo::Bar& t) {
in >> t.str;
return in;
}
不管怎样,非常感谢您的帮助!感谢您没有亲自给我提供解决方案;通过自己弄清楚来学习要好得多,即使我确实得到了一些帮助,为我指明了正确的方向。