回 帖 发 新 帖 刷新版面

主题:一个由类组成的容器,如何调用类中的函数

#include<iostream>
#include<string>
#include<vector>
using namespace std;
class employee
{
public:
    string Name;
    string Role;//boss,salesman,intern
    double Salary;
    employee()
    {
    }
    employee(string name,string role)
    {
        Name=name;
        Role=role;
    }
    virtual double cacsalary()=0;
    virtual void show()=0;
};
class boss:public employee
{
public:
    boss()
    {
    }
    boss(string name,string role):employee(name,role)
    {
    }
    double cacsalary()
    {
     
        return 5000;
    }
    
    void show()
    {
        cout<<"the information are:"<<endl;
        cout<<"Name:"<<Name<<endl;
        cout<<"Role:"<<Role<<endl;
        cout<<"Salary:"<<cacsalary()<<endl;
    }
};
class salesman:public employee
{
public:
    int N;
    salesman(string name,string role,int n):employee(name,role)
    {
        N=n;
    }
    double cacsalary()
    {
        return 2000+N*0.1;
    }
    void show()
    {
        cout<<"the information are:"<<endl;
        cout<<"Name:"<<Name<<endl;
        cout<<"Role:"<<Role<<endl;
        cout<<"Salary:"<<cacsalary()<<endl;
    }
};
class intern:public employee
{
public:
    int T;
    intern(string name,string role,int t):employee(name,role)
    {
        T=t;
    }
    double cacsalary()
    {
        return T*30;
    }
    void show()
    {
        cout<<"the information are:"<<endl;
        cout<<"Name:"<<Name<<endl;
        cout<<"Role:"<<Role<<endl;
        cout<<"Salary:"<<cacsalary()<<endl;
    }
};



void main()

{
    vector<employee *> empList;
    employee *pe = new boss("John","boss");
    empList.push_back(pe);

    pe=new salesman("Lisa","salesman",10000);
    empList.push_back(pe);
    pe=new intern("Kash","intern",100); 
    empList.push_back(pe);

    double totalSalary=0;
        for(int i=0;i<empList.size();i++)
        {
            totalSalary+=empList[i].cacsalary();
        }
    cout<<"the totalSalary is:"<<totalSalary<<endl;
    

}

回复列表 (共2个回复)

沙发

类对象调用成员,是 a.b();
类指针对象调用成员,是 pa->b();

板凳

就和普通的指针调用是一样的,容器中的迭代器就是特殊的指针而已,呵呵。
     把main()中的totalSalary+=empList[i].cacsalary();改为totalSalary+=empList[i]->cacsalary();就ok了。

我来回复

您尚未登录,请登录后再回复。点此登录或注册