C++ 在运算符
我为命名空间中的一个类编写了一个ostream操作符,该命名空间包含在不同命名空间中定义了ostream操作符的对象 试图在编写原始问题时使用时发生编译错误,因此我找到了解决方案,但我不理解为什么需要添加using语句C++ 在运算符,c++,namespaces,ostream,C++,Namespaces,Ostream,我为命名空间中的一个类编写了一个ostream操作符,该命名空间包含在不同命名空间中定义了ostream操作符的对象 试图在编写原始问题时使用时发生编译错误,因此我找到了解决方案,但我不理解为什么需要添加using语句 似乎UnitTest::Operator最好使用实用工具:operator@40two:关于范围的公平点-你知道为什么首先需要它吗?对于我来说,移动using namespace实用程序的方式仍然没有意义;将行插入命名空间UnitTest,而不是将其置于全局范围。问题在于Unit
似乎UnitTest::Operator最好使用实用工具:operator@40two:关于范围的公平点-你知道为什么首先需要它吗?对于我来说,移动using namespace实用程序的方式仍然没有意义;将行插入命名空间UnitTest,而不是将其置于全局范围。问题在于UnitTest::运算符
#define USEOSTREAM 1
#include <iostream>
#include <vector>
namespace Common {
struct Foo {
public:
Foo(int val=0) : mVal(val) {}
int mVal;
};
}
namespace Utility {
std::ostream& operator<<(std::ostream& out, const Common::Foo& obj) {
out << obj.mVal;
return out;
}
}
using namespace Utility;
namespace UnitTest {
class Bar {
public:
Bar(int val=0) : foo(val) {}
Common::Foo foo;
};
#if USEOSTREAM
std::ostream& operator<<(std::ostream& out, const Bar& bar) {
out << bar.foo; // Compile Error : no operator found of type 'const Common::Foo'
// Utility::operator<<(out,vec[i]) << " " ; // No compile error for fully qualified name
return out;
}
void printBar(const Bar& b) {
std::cout << b;
}
#else
std::ostream& print(std::ostream& out, const Bar& bar) {
out << bar.foo; // No Compile Error
return out;
}
void printBar(const Bar& b) {
print(std::cout,b);
}
#endif
void test01() {
printBar(Bar(123));
}
}
int main (int,char**) {
UnitTest::test01();
return 0;
}
using Utility::operator<<; // New Line
std::ostream& operator<<(std::ostream& out, const Bar& bar) {
out << bar.foo;
return out;
}