在下面的代码中,有人可以解释为什么如果启用了由“ifdef TEST”分隔的代码,我定义的将枚举打印为字符串的 operator<< 函数没有被使用。在我看来,导致我的问题的代码应该与类 Container 中枚举的打印无关,特别是因为问题代码引用了不同的类(Container2)。
如果我使用 g++ filename.cpp 构建,则输出为:
Print for Container: mycolor is red
如果我使用 g++ -DTEST filename.cpp 构建,则输出为:
Print for Container: mycolor is 0
代码如下:#include
namespace mynamespace
{
enum color {red, blue};
}
namespace mynamespace
{
class Container
{
public:
mynamespace::color mycolor1;
explicit Container() : mycolor1(mynamespace::red) {};
std::ostream &Print(std::ostream& os) const;
};
class Container2
{
};
}
std::ostream & operator<<(std::ostream &os, const mynamespace::color &_color);
namespace mynamespace
{
#ifdef TEST
// If this is defined, the printing of the enum in Container does not use the operator<< function to output the enum as a string
std::ostream& operator<<(std::ostream &os, const Container2 &i);
#endif
}
int main()
{
// Create a Container. Default color is red
mynamespace::Container *container = new mynamespace::Container;
container->Print(std::cout);
}
std::ostream & mynamespace::Container::Print(std::ostream &os) const
{
os << "Print for Container: mycolor is " << mycolor1 << std::endl;
return os;
}
std::ostream& operator<<(std::ostream &os, const mynamespace::color &_color)
{
switch(_color)
{
case mynamespace::red: os << "red"; break;
case mynamespace::blue: os << "blue"; break;
default: os << "unknown"; break;
}
return os;
}