处理我自己的异常类

处理我自己的异常类

我在显示子类中的某些字符串时遇到问题。我正在尝试使用一个函数,但是我不确定为什么我没有得到这些字符串的内容。

class Employee{
    string FN, LN, JT;
    double Income;

public:
    char const *getters(){
        return FN.data(), LN.data(), JT.data(); //=========>getting the content of strings
    }
    virtual char const *getAccess()=0;
    Employee(char const *fn, char const *ln, char const *jt, double inc){

        if(fn==0) throw Exception(1, "Sorry, First Name is Null");
        if(ln==0) throw Exception(2, "Sorry, Last Name is Null");
        if(jt==0) throw Exception(3, "Sorry Job Title is Null");
        if(inc<=0) throw Exception(4, "Sorry, The Income is Null");

        FN=fn;
        LN=ln;
        JT=jt;
        Income=inc;
    }
};

class Programmer: public Employee{
public:
    Programmer(char const *fn, char const *ln, double inc):
        Employee(fn,ln,"Programmer", inc)
    {}
    char const *getAccess(){
        return "You have access to Meeting Room + Development Office";
    }
};

//=========The Main============
int main(){
    Employee *acc[3];

    try{
        acc[0]=new Programmer("Juan", "Villalobos", 60000);
        acc[1]=new Director("Jorge", "Villabuena", 70000);
        acc[2]=new ProdSupport("Pedro", "Villasmil", 80000);
        for(int i=0; i<3; i++){
            cout << acc[i]->getters() << endl;    //=============>Displaying the strings
            cout << acc[i]->getAccess() << endl;
        }
    } catch(Exception acc){
        cout << "Err:" << acc.getErrCode() << " Mess:" << acc.getErrMess() << endl;
    }

    return 0;
}


因此,我猜测我的函数没有执行我想要的操作,即显示名字和姓氏。
我究竟做错了什么?

最佳答案

我不理解混合char*string的意义。优先选择后者。

这确实可以编译

char const *getters(){
    return FN.data(), LN.data(), JT.data();
}


但是你可能想要的是

char const *getters(){
    return (FN + LN + JT).data();
}


我会这样重新编写您的程序:

class Employee{
    string FN, LN, JT;
    double Income;

public:
    string getters(){
        return FN + " " + LN + " " + JT;
    }

    virtual string getAccess()=0;

    Employee(string const &fn, string const &ln, string const &jt, double inc) :
        FN(fn), LN(ln), JT(jt), Income(inc)
    {
    }
};

class Programmer: public Employee{
public:
    Programmer(string const &fn, string const &ln, double inc):
        Employee(fn,ln,"Programmer", inc)
    {}

    string getAccess(){
        return "You have access to Meeting Room + Development Office";
    }
};

//=========The Main============
int main()
{
    std::vector<Employee> acc;

    acc.push_back(Programmer("Juan", "Villalobos", 60000));
    acc.push_back(Director("Jorge", "Villabuena", 70000));
    acc.push_back(ProdSupport("Pedro", "Villasmil", 80000));

    for(size_t i=0; i<acc.size(); i++){
        cout << acc[i].getters() << endl;
        cout << acc[i].getAccess() << endl;
    }

    return 0;
}

关于c++ - C++处理我自己的异常类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18197780/

10-11 06:32