重载运算符<<不管用

时间:2016-06-02 06:00:23

标签: c++ c++11

class Employee
{
public:
    Employee(const string& fName, const string& lName, float salary) {
        mSalary = salary;
        mFirstName = fName;
        mLastName = lName;
    }

    static Employee create() {
        string input1, input2; 
        float sal; 
        cout << "Enter first name: ";
        cin >> input1;
        cout << "\nEnter last name: ";
        cin >> input2;
        cout << "\nEnter salary here: ";
        cin >> sal;
        cout << "\n";
        Employee emp(input1, input2, sal);
        return emp;
    }

    virtual void printStats() {
        cout << "===============================================\n";
        cout << "First name:\t\t" << mFirstName << endl;
        cout << "Last name:\t\t" << mLastName << endl;
        cout << "Salary:\t\t\t" << mSalary << endl;
    }

    friend ostream& operator<<(ostream& outFile, Employee& emp) {
        emp.print(outFile);
        return outFile;
    }


    virtual string getName() {
        return mFirstName;
    }

protected:
    virtual void print(ostream& str) {
        str << "Name: " << mFirstName << " " << mLastName << endl;
        str << "Salary" << mSalary << endl;
    }
    string mFirstName;
    string mLastName; 
    float mSalary;
};

在名为database的单独类中,我有这个方法:

void showEmployees() {
        int counter = 1;
        for (Employee* e : data) {
            cout << "\n["<<counter<<"]\n"<<e<<"\n";
            counter++;
        }
    }

当我使用这种方法时,我只得到内存地址。另外我知道实现是在头文件中(我只是懒惰)。

Making operator<< virtual?

我在这里遵循了这个建议,这样我就可以有效地将员工插入到一个ostream对象中,但它只是给了我一个内存地址......我得到了那个返回的ostream&amp;会给我一个地址,但我不知道我还能做些什么。

3 个答案:

答案 0 :(得分:1)

您正在尝试打印指向cout << "\n[" << counter << "]\n" << *e << "\n"; 的指针,这就是您获取地址的原因。只需取消引用指针:

{{1}}

答案 1 :(得分:0)

e是指向此处定义的Employee的指针:

for (Employee* e : data) {

因此,如果您打印,则打印一个地址。如果要打印e指向的值,则需要取消引用它:

cout << "\n[" << counter << "]\n" << *e << "\n";
//                                   ^-- here

答案 2 :(得分:0)

您的问题在于,您将插入运算符定义为:

ostream& operator<<(ostream& outFile, Employee& emp)

你通过传递一个指针来调用它......

.....
for (Employee* e : data) {
        cout << "\n["<<counter<<"]\n"<<e<<"\n";
        .....

您应该重新定义您的运营商,以Employee:{/ p>来const&

ostream& operator<<(ostream& outFile, const Employee& emp)

并称之为:

.....
for (Employee* e : data) {
        cout << "\n["<<counter<<"]\n"<< *e<<"\n";
        .....

另外,请考虑const-correctness并将const添加到print memeber函数中。

virtual void print(ostream& str) const;