Accessors and Mutators C++

空扰寡人 提交于 2020-05-28 05:20:20

问题


I am currently trying to learn C++ and following an instruction. I've researched on mutators and accessors but I need a simple explanation.

class Customer
{
public:
    Customer();
    ~Customer();

private:
    string m_name;
    int m_age;

};

Right the code above is in a header file. Within the instructions it is asking me to set a public accessors and mutator for both data. How do I do this?

Also it mentions checking the age is not negative in the mutator. I know how to implement the code but I'm just confused on where to place it. Do I place the validation in this header file? or in the .cpp? or in the main method?

I know this sounds all silly and I'm sure simple but I'd like to try and understand this.


回答1:


Please note that this is basic C++.

Accessor - Member function used to retrieve the data of protected members.

Mutators - Member function used to edit the data of protected members.

In your case,

class Customer
{
public:
    Customer();
    ~Customer();
    string getName(); // Accessor for the m_name variable
    void editName(string in); // Mutator for the m_name variable

private:
    string m_name;
    int m_age;

};

Inside your .cpp file:

string Customer::getName() {
    return m_name;
}

void Customer::editName(string in) {
    m_name = in;
}


来源:https://stackoverflow.com/questions/28702808/accessors-and-mutators-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!