gpt4 book ai didi

c++ - 如何重载 << 运算符以便将对象的数据写入文件?

转载 作者:行者123 更新时间:2023-12-04 20:51:21 26 4
gpt4 key购买 nike

我有一个 piggyBank 类型的对象,我需要将这个对象的数据写入一个文件,然后读取它。我知道如何写入/读取文本文件,但如何重载 << 运算符以便将有关对象的数据写入文件?

我在这里类的代码:

piggyBank.h

#include <string>
#ifndef PIGGYBANK_H
#define PIGGYBANK_H

class PiggyBank
{
private:
std::string owner;
int balance;
bool broken;
int id;
static int nrOfObjects;
public:
PiggyBank(void);
PiggyBank(std::string name);
std::string getOwnerName() const;
void setOwnerName(std::string name);
bool isBroken() ;
int getBalance(int & amount) ;


};



#endif /* PIGGYBANK_H */

piggyBank.cpp

#include "PiggyBank.h"
#include "readWrite.h"
#include <string>
#include <iostream>
using namespace std;

int PiggyBank::nrOfObjects = 0; // outside constructor


PiggyBank::getNrOfObjects(){

return nrOfObjects;

}

PiggyBank::PiggyBank(void){
{this->owner="";this->balance=0;this->broken=false;}
id = ++nrOfObjects;

}


PiggyBank::PiggyBank(std::string name, int startBalance){
{this->owner=name;this->balance=startBalance;this->broken=false;}
id = ++nrOfObjects;
}

string PiggyBank::getOwnerName() const{
return this->owner;
}
void PiggyBank::setOwnerName(string name){
this->owner = name;
}
bool PiggyBank::isBroken() {
return this->broken;
}

int PiggyBank::getBalance(int & amount) {
if(!broken){
amount = balance;
return 0;
}else{
return -1;
}
}

最佳答案

你想要 << operator成为friend上课和return ostream& .这是一个简单的示例,可以了解它的工作原理。

friend ostream& operator << (ostream& os, const PiggyBank& obj)
{
// For example something like this
os << "Information that you want to output to the file:\n";
os << "Owner: " << obj.owner << "\n";
return os;
}

然后你可以像这样使用它:

PiggyBack obj;
ofstream fout("file.txt");

// also check to see if the file opened correctly
if(fout.fail())
{
cout << "File failed to open\n";
return 0;
}
fout << obj;
// now you have written the owner information onto the file as well as the message before it
// inside the operator<< overload

// close the resource at the end
fout.close();

很酷的部分是您也可以使用它通过更改 fout 来打印到控制台成为cout .例如:

cout << obj; // will print to the console

关于c++ - 如何重载 << 运算符以便将对象的数据写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59230692/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com