除了main之外还从非memebr函数调用成员函数?

时间:2017-09-30 00:58:56

标签: c++

#include <iostream>             
#include <fstream>
#include <string>       
using namespace std;

class Name
{
public:
    string firstname;
    string lastname;

};

class Adress
{
public:
    string housenum;
    string stname;
};

class Person
{
    Name name;
    Adress adress;
    public:
    void readData(ifstream &cfile);
    void printData(ofstream &outfile);

};
void read(Person);                    // function prototypes
void print(Person);

int main()
{
    Person jeffrey;
    cout << " Please enter a first and last name " << endl;
    read(jeffrey);
    print(jeffrey);

    return 0;
}

我试图让函数read调用成员函数readData来读取名称。但是当程序编译并运行时。我被提示输入名称,但之后它不输出它。看起来它输出一个空字符串。当readDataprintData直接从main调用时,它可以工作和输出,但在从其他函数调用时则不会。请帮助。

void read(Person M)
{
    ifstream cfile("con");
    M.readData(cfile);
    cfile.close();
    return;
}
void print(Person M)
{
    ofstream outfile("con");
    M.printData(outfile);
    outfile.close();
    return;
}
void Person::readData(ifstream &cfile)
{
    cfile >> name.firstname;

    cfile >> name.lastname;

    return;
}

void Person::printData(ofstream &outfile)
{
    outfile << name.firstname << endl;
    outfile << name.lastname << endl;
    return;
}

0 个答案:

没有答案