学习类定义中的获取器和设置器

One of the advantages of using classes for objects in C++ is you can hide the member variables by making their access private. Doing so, though, makes it impossible to access those variables or change their values from outside the class definition. One solution to this problem is to provide a set of member functions called getters and setters in your class interface. I will cover how to create and use getters and setters in this article.

在C ++中为对象使用类的优点之一是,可以通过将成员变量设为私有来隐藏成员变量。 但是,这样做将无法从类定义之外访问这些变量或更改其值。 解决此问题的一种方法是在类接口中提供一组成员函数,称为getter和setter。 我将在本文中介绍如何创建和使用getter和setter。

为什么班级需要吸气剂和吸气剂 (Why Classes Need Getters and Setters)

The convention when designing a C++ class is to make the member variables private to control access to them. With data hiding, you can write code that checks the data coming into a class to make sure it is valid before assigning it to member variables.

设计C ++类时的惯例是将成员变量设为私有,以控制对其的访问。 使用数据隐藏,您可以编写代码以检查进入类的数据,以确保在将其分配给成员变量之前该数据是有效的。

For example, if a class is storing a person’s age, by marking the member variable as private you can provide access to the variable through a function that first checks to make sure the data being passed in is a valid age. If not, you can assign a default value or ask the user to enter the data in again.

例如,如果一个班级正在存储一个人的年龄,则可以通过将成员变量标记为私有来将其标记为私有,从而可以通过一个函数进行访问,该函数首先检查以确保传入的数据是有效年龄。 如果没有,您可以分配一个默认值或要求用户再次输入数据。

Without this check, the data entered for an age can be any legal value allowed for that type by the compiler. So an age passed to an integer variable can be 34 or it can be 123,345 since those are both valid integer values. A data validating function can stop illegal values from entering the object and preserving the integrity of the data.

如果不进行此检查,则输入的有效期数据可以是编译器对该类型允许的任何合法值。 因此,传递给整数变量的年龄可以是34,也可以是123,345,因为它们都是有效的整数值。 数据验证功能可以阻止非法值进入对象并保持数据的完整性。

Since a member variable marked as private cannot be accessed in any matter, a class must also provide means for the data stored in a member variable to be retrieved from an object, if that is part of the design. This function is not as important for maintaining data integrity but it is usually a practical necessity.

由于标记为私有的成员变量无论如何都无法访问,因此,如果这是设计的一部分,则类还必须提供一种方法,用于从对象中检索成员变量中存储的数据。 该功能对于保持数据完整性并不重要,但通常是实际必需的。

Our object-oriented programs can meet these data setting and data retrieval needs by providing getter and setter member functions as part of the class interface.

我们的面向对象程序可以通过提供getter和setter成员函数作为类接口的一部分来满足这些数据设置和数据检索需求。

创建设置器功能 (Creating Setter Functions)

Let’s start by defining a simple Person class to use for this article. This class will have two member variables — name and age. The age member variable will require some data validation since an age can’t be less than 0 and should have an upper bound of about 120.

让我们从定义一个简单的Person类开始,以用于本文。 此类将具有两个成员变量nameageage成员变量将需要一些数据验证,因为年龄不能小于0,并且上限应为120。

Let’s start with just the bare bones definition for the class:

让我们从该类的基本定义开始:

class Person {
private:
string name;
int age;public:
Person(string n, int a) {
name = n;
age = a;
} void display() {
cout << name << ", " << age << endl;
}
};

Now let’s design a setter function for the class. The function needs to check the age passed in as the argument to make sure it is greater than or equal to 0 and less than or equal to 120. I’ll also arbitrarily decide that if the age being entered is invalid, the function will just set the age to 0.

现在让我们为该类设计一个setter函数。 该函数需要检查作为参数传入的年龄,以确保它大于或等于0且小于或等于120。我还将任意决定,如果输入的年龄无效,该函数将将年龄设置为0。

Here is the definition for a setAge function:

这是setAge函数的定义:

void setAge(int a) {
if ((a >= 0) && (a <= 120)) {
age = a;
}
else {
age = 0;
}
}

Just add this definition to the class definition. Now here’s a short program to test our new setter function:

只需将此定义添加到类定义即可。 现在这是一个简短的程序,用于测试我们的新setter函数:

int main ()
{
Person me("Jane Doe", 34);
me.display();
cout << endl;
me.setAge(121);
me.display();
return 0;
}

The output from this program is:

该程序的输出为:

Jane Doe, 34
Jane Doe, 0

Now that we’ve written this setter function, we can reuse it in other places, such as in the constructor:

现在,我们已经编写了此setter函数,可以在其他地方(例如在构造函数中)重用它:

Person(string n, int a) {
name = n;
setAge(a);
}

We need the data validation of this function in the constructor as well. Here’s a test program to check the new constructor definition:

我们还需要在构造函数中对此函数进行数据验证。 这是一个检查新构造函数定义的测试程序:

int main ()
{
Person you("Bobby McGee", -1);
you.display();
return 0;
}

The output from this program is:

该程序的输出为:

Bobby McGee, 0

Let’s wrap up the setter functions for the Person class by defining a setter function for the name member variable:

让我们通过为name成员变量定义一个setter函数来包装Person类的setter函数:

void setName(string n) {
name = n;
}

That’s all there is to it. For consistency purposes, we should add this function to our constructor also, like this:

这里的所有都是它的。 为了保持一致性,我们还应该将此函数添加到构造函数中,如下所示:

Person(string n, int a) {
setName(n);
setAge(a);
}

After I’ve finished discussing getter functions I’ll show the complete class definition.

在讨论完getter函数之后,我将展示完整的类定义。

创建吸气功能 (Creating Getter Functions)

Getter functions are easier to define as they just need to retrieve the data stored in a class object. Here are the getter functions for the Person class:

Getter函数更易于定义,因为它们只需要检索存储在类对象中的数据。 以下是Person类的getter函数:

string getName() {
return name;
}int getAge() {
return age;
}

Here is the complete Person class definition with all the getter and setter functions included:

这是完整的Person类定义,其中包括所有getter和setter函数:

class Person {
private:
string name;
int age;public:
Person(string n, int a) {
setName(n);
setAge(a);
} void display() {
cout << name << ", " << age;
} void setAge(int a) {
if ((a >= 0) && (a <= 120)) {
age = a;
}
else {
age = 0;
}
} void setName(string n) {
name = n;
}
string getName() {
return name;
} int getAge() {
return age;
}
};

结语 (Wrapping Up)

Getter and setter functions are an important addition to the class interface. Since the member variables of a class will be marked as private, the users of your class will need some means of retrieving and setting their values. Getter and setter functions provide this access in a safe manner, since setter functions can be written with data validation code included to make sure that member variables are set to valid values.

Getter和setter函数是类接口的重要补充。 由于类的成员变量将被标记为私有,因此类的用户将需要一些方法来检索和设置其值。 Getter和setter函数以安全的方式提供此访问权限,因为setter函数可以使用包含的数据验证代码来编写,以确保将成员变量设置为有效值。

Of course, there are situations when you don’t want to provide either getter or setter functions or both for all member variables in a class. Member variables that can be retrieved but not set are called read-only member variables. An example of such a member variable might be a static class variable that keeps track of the number of object instances during a program run. This value should be read-only so that the user doesn’t accidentally change the value.

当然,在某些情况下,您既不想为类中的所有成员变量都提供getter或setter函数,也不想提供它们。 可以检索但无法设置的成员变量称为只读成员变量。 此类成员变量的一个示例可能是静态类变量,该类变量在程序运行期间跟踪对象实例的数量。 该值应该是只读的,以便用户不会意外更改该值。

Thanks for reading this article and please email me at mmmcmillan1@att.net with comments and suggestions. If you are interested in my online programming courses, please visit https://learningcpp.teachable.com.

感谢您阅读本文,请给我发电子邮件mmmmmillan1@att.net并提供评论和建议。 如果您对我的在线编程课程感兴趣,请访问https://learningcpp.teachable.com

翻译自: https://levelup.gitconnected.com/learning-c-getters-and-setters-in-class-definitions-c7c0469fb63c

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值