无法访问对象向量中的成员函数

时间:2015-03-11 21:17:55

标签: c++ vector

我试图简单地创建一个对象向量,向其添加一个对象,然后通过访问函数" getter"来在向量中的该对象中显示一些变量。代码编译但它没有显示返回字符串的函数和返回double的函数的垃圾编号。我确信这很简单....你可以帮忙(在几个小时内完成任务:S)?

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

class Employee
{
    string fName, lName;
    double weeklyIncome, grossSales, bonus;
public:
    Employee(){};
    Employee(string fn, string ln, double sales)
    {
        fName = fn;
        lName = ln;
        grossSales = sales;
        bonus = sales * 0.09;
        weeklyIncome = 200;
    }
    double getNetIncome() {return bonus + weeklyIncome;}
    string getfName() {return fName;}
    double getgrossSales() {return grossSales;}
    ~Employee(){};
};

int main()
{
    vector<Employee> salespeople(15);
    Employee e1("John", "Smith", 5000);
    salespeople.push_back(e1);
    cout << salespeople[0].getNetIncome();
    cout << salespeople[0].getgrossSales();
    cout << salespeople[0].getfName();
    system("pause");
    return 0;
}

1 个答案:

答案 0 :(得分:0)

vector<Employee> salespeople(15);      // This creates a vector of 15 elements
Employee e1("John", "Smith", 5000);
salespeople.push_back(e1);             // Now you have added the 16-th element
cout << salespeople[0].getNetIncome(); // The first element is still the default
                                       // constructed element.
cout << salespeople[0].getgrossSales();
cout << salespeople[0].getfName();

您可以使用

解决问题
vector<Employee> salespeople;  // Create an empty vector and then
                               // add items to it.

或通过更改

salespeople.push_back(e1);

salespeople[0] = e1;

建议改进

更改默认构造函数以将double变量初始化为合理的值。

Employee() : weeklyIncome(0.0), grossSales(0.0) bonus(0.0) {};