And*_*bor 0 c++ file-io stream
我在 C++ 中遇到了“没有运算符“<<”匹配这些操作数”错误(在 fout << dog 处)的问题。这是我的代码的样子:
int FileRepository::addDog(const Dog& dog)
{
if (this->findDog(dog.getName()) != -1)
return -1;
std::ofstream fout;
fout.open(this->fileName.c_str(), std::ios_base::app);
fout << dog;
fout.close();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
ostream& operator<<(ostream& outputStream, Dog& dog)
{
outputStream << dog.name << ", " << dog.breed << ", " << dog.birthDate << ", " << dog.numberOfShots << ", " << dog.photo << ", " << '\n';
return outputStream;
}
Run Code Online (Sandbox Code Playgroud)
我还导入了特定的头文件和库,并且“>>”运算符有效。
在这里它有效:
void FileRepository::writeVectorToFile(std::vector<Dog> vectorOfDogs)
{
ofstream fout(this->fileName.c_str());
for (Dog dog : vectorOfDogs)
fout << dog;
fout.close();
}
Run Code Online (Sandbox Code Playgroud)
在运算符中,第二个参数不是常量引用
ostream& operator<<(ostream& outputStream, Dog& dog)
{
outputStream << dog.name << ", " << dog.breed << ", " << dog.birthDate << ", " << dog.numberOfShots << ", " << dog.photo << ", " << '\n';
return outputStream;
}
Run Code Online (Sandbox Code Playgroud)
而在成员函数中,则使用了对对象的常量引用。
int FileRepository::addDog(const Dog& dog)
Run Code Online (Sandbox Code Playgroud)
像这样声明操作符
ostream& operator<<(ostream& outputStream, const Dog& dog)
{
outputStream << dog.name << ", " << dog.breed << ", " << dog.birthDate << ", " << dog.numberOfShots << ", " << dog.photo << ", " << '\n';
return outputStream;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
44 次 |
| 最近记录: |