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

时间:2015-04-10 21:36:12

标签: c++

我在将一些数据写入文件时遇到了麻烦。

#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 Class中提取Person类中的数据。 我的目标是能够在文件的不同行上打印出名字,姓氏和工资。到目前为止只有工资..

更新

我在类Person中添加了一些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   

3 个答案:

答案 0 :(得分:2)

这是你指的是什么?

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

然后:

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

或者你可以试试这个解决方案(如果我们坚持你的例子):

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

答案 1 :(得分:1)

您收到错误是因为您假设在函数名末尾使用()括号调用该函数。所以这就像Giorgi的答案。对于getName()函数来说,将名字和姓氏作为字符串返回而不是作为Person返回更有意义(因为你应该将函数重命名为getPerson)。如果您希望getName函数返回名称,则需要将返回类型更改为字符串,然后将函数定义更改为以下内容:

string Employee::getName()
{
    return hiredHand.getFirst() + " " + hiredHand.getLast();
}

为了进一步参考,让Employee类派生自Person更有意义,因为员工是一个人,我希望他/她是......:P

答案 2 :(得分:1)

这是我正在寻找的代码:)

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