gpt4 book ai didi

c++ - 将两个相关类的数据写入文件

转载 作者:行者123 更新时间:2023-11-30 01:49:06 26 4
gpt4 key购买 nike

我在将一些数据写入文件时遇到问题。

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>

using namespace std;

class Person{
public:
Person();
Person(string, string);
string getFirst();
string getLast();
private:
string firstName, lastName;
};

class Employee{
public:
Employee::Employee();
Employee(string, string, float);
Person getName();
float getPay();
private:
Person hiredHand;
float salary;
};

Person::Person()
:firstName(""), lastName("")
{
}

Person::Person(string first, string last)
: firstName(first), lastName(last)
{
}

string Person::getFirst()
{
return firstName;
}

string Person::getLast()
{
return lastName;
}

Employee::Employee()
: hiredHand("", ""), salary(0)
{
}

Employee::Employee(string first, string last, float sal)
: hiredHand(first, last), salary(sal)
{
}

Person Employee::getName()
{
return hiredHand;
}

float Employee::getPay()
{
return salary;
}

int main()
{
string first, last;
float salary;

cout << "Enter a first name, last name, and a salary." << endl;
cin >> first >> last >> salary;
Employee person1(first, last, salary);

ofstream fileOut("Output.txt");
if (!fileOut)
{
cerr << "Unable to open file for reading." << endl;
exit(1);
}

Person guy1 = person1.getName();

fileOut << guy1.getFirst << endl;
fileOut << guy1.getLast << endl;
fileOut << fixed << setprecision(2) << "$" << person1.getPay() << endl;
fileOut.close();
}

我不确定如何从 Employee 类中提取 Person 类中的数据。我的目标是能够在文件的不同行中打印出名字、姓氏和薪水。到目前为止只有工资有效..

更新:

我已经向 Person 类添加了一些 setter/getter ,但是当我尝试打印它时它给了我一个错误。

Error1: error C3867: 'Person::getFirst': function call missing argument list; use '&Person::getFirst' to create a pointer to member 
Error2: error C3867: 'Person::getLast': function call missing argument list; use '&Person::getLast' to create a pointer to member

最佳答案

你指的是这个吗?

string Person::getFirstName()
{
return firstName;
}

然后:

string Employee::getFirstName()
{
return hiredHand.getFirstName();
}

或者,您可以改为尝试此解决方案(如果我们坚持您的示例):

fileOut << guy1.getFirst() << endl;
fileOut << guy1.getLast() << endl;

关于c++ - 将两个相关类的数据写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29571073/

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