存取器和变异器C ++ [英] Accessors and Mutators C++

查看:128
本文介绍了存取器和变异器C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试学习C ++并按照说明进行操作.我已经研究了变异子和存取子,但我需要一个简单的解释.

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?

此外,它还提到了检查变量中的年龄是否为负数.我知道如何实现代码,但是我对放置它的位置感到困惑.是否将验证放置在此头文件中?或在.cpp中?或在主要方法中?

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.

推荐答案

请注意,这是基本的C ++.

Please note that this is basic C++.

访问器-成员函数,用于检索受保护成员的数据.

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

Mutators -成员函数,用于编辑受保护成员的数据.

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

就您而言,

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;

};

在.cpp文件中:

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

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

这篇关于存取器和变异器C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆