您不能向 中添加额外的参数operator<<
,但您可以轻松定义采用详细参数的自定义打印函数:
void dump(ostream& ostr, const myClass& obj, int verbosity = 1)
{
if (verbosity > 2)
ostr << "Very verbose!\n";
if (verbosity > 1)
ostr << "Verbose!\n";
if (verbosity > 0)
ostr << "Standard!\n";
ostr << "Minimal.\n";
}
用法:
dump(cout, myobj); // Default
dump(cout, myobj, 0); // Minimal
dump(cout, myobj, 1); // Default
dump(cout, myobj, 2); // Verbose
dump(cout, myobj, 3); // Very verbose
您还应该提供一个流操作符转发到dump()
,使用默认的详细程度:
ostream& operator<<(ostream& ostr, const myClass& obj)
{
dump(ostr, obj);
return ostr;
}
如果您想遵循这种方式,最好enum
为详细程度声明 an 而不是使用int
s:
enum Verbosity
{
MinimalOutput = 0,
StandardOutput = 1,
VerboseOutput = 2,
DebugOutput = 3
};