我对编码有点陌生,需要为某种数据库做一个程序。 我在YouTube上看到了某个家伙的教程,复制了他的代码,但是我收到一个错误,我不知道如何解决它。
错误:没有运算符"=="匹配这些操作数;引用if(outs == cout)
这是代码:
void Employee::output(ostream& outs)
{
if (outs == cout)
{
outs << "Name: " << name << endl;
outs << "ID number: " << id_number << endl;
outs << "Address: " << address << endl;
outs << "Salary: " << salary << endl;
outs << "Years worked at company: " << year_started << endl;
}
else {
outs << name << endl;
outs << id_number << endl;
outs << address << endl;
outs << salary << endl;
outs << year_started << endl;
}
}
这是我声明输出的方式:
void output(std::ostream& outs);
添加了带有 #include <> 的 iostream 和字符串
Stream 对象没有可比性,但您可以比较它们的地址:
if ( & outs == & cout )
您无法比较流的相等性。
相反,您可以实现不同的功能,一个用于cout
,一个用于fstream
。
我建议使用两种不同的功能,请注意,一个有提示,另一个没有。
您可以使用完全不同的方法来创建调试输出,该方法不依赖于比较要写入的流是否std::cout
。此方法依赖于标志是否已打开。
创建帮助程序namespace
帮助程序namespace
可以保存数据并提供方便的功能来操作数据。
namespace Employee_NS
{
bool writeVerbose = false;
template <bool val>
std::ostream& verbose(std::ostream& outs)
{
writeVerbose = val;
return outs;
}
std::ostream& operator<<(std::ostream& outs, std::ostream& (*fun)(std::ostream&))
{
return fun(outs);
}
};
以不同的方式实施Employee::output
将返回类型从void
更改为std::ostream&
,并使函数成为const
成员函数。
std::ostream& Employee::output(std::ostream& outs) const
{
if ( Employee_NS::writeVerbose )
{
outs << "Name: " << name << std::endl;
outs << "ID number: " << id_number << std::endl;
outs << "Address: " << address << std::endl;
outs << "Salary: " << salary << std::endl;
outs << "Years worked at company: " << year_started << std::endl;
}
else {
outs << name << std::endl;
outs << id_number << std::endl;
outs << address << std::endl;
outs << salary << std::endl;
outs << year_started << std::endl;
}
return outs;
}
添加合适的operator<<
函数
添加非成员函数,以便能够以直观的方式使用Employee
对象。
std::ostream& operator<<(std::ostream& out, Employee const& e)
{
return e.output(out);
}
现在,您可以创建详细输出,无论输出是进入文件还是std::cout
。
Employee e;
// Verbose output to cout
std::cout << Employee_NS::verbose<true> << e;
std::ofstream out("test.txt");
// Verbose output to the file
out << Employee_NS::verbose<true> << e;
// Non-verbose output to the file
out << Employee_NS::verbose<false> << e;
此方法提升了是否为调用函数创建详细输出的决定。它还提供了在任何输出目标中创建详细输出的功能。