c:foreach i++_学习C ++:类简介

c:foreach i++

The primary way to create objects for doing object-oriented programming in C++ is the class. A class is a set of variables (called member variables) and functions (called member functions) that define the properties and behaviors of a real-world (or abstract) object. In this article I’m going to introduce the fundamentals of creating class objects in C++.

类是创建对象以进行C ++中的面向对象编程的主要方式。 类是定义实际对象(或抽象对象)的属性和行为的一组变量(称为成员变量)和函数(称为成员函数)。 在本文中,我将介绍在C ++中创建类对象的基础。

对象概述 (An Overview of Objects)

Object-oriented programming developed as a means of better modeling the real world. In the real world, the problems we want to solve via computer programs involve things, which are identified as nouns. A payroll program, for example, will have employees, a payroll, a paycheck, etc. All of these are things we can identify as objects.

开发了面向对象的程序设计,以更好地模拟现实世界。 在现实世界中,我们要通过计算机程序解决的问题涉及事物,这些事物被标识为名词。 例如,薪资计划将有员工,薪资,薪水等。所有这些都是我们可以识别为对象的东西。

These objects have properties that define them and behaviors that describe what they do. For example, an employee has a name, a position of employment, an age, etc. An employee behavior for a payroll program may be the number of hours they worked in a pay period.

这些对象具有定义它们的属性和描述它们做什么的行为。 例如,雇员有姓名,工作职位,年龄等。雇员在工资核算程序中的行为可能是他们在工资期内工作的小时数。

The primary concept behind C++ classes is that we can combine the properties of a thing with the behavior of the thing into a single entity — the class. Another fundamental concept is that the properties of an object can be hidden so that access to those properties can be controlled to regulate the data that is stored in the object.

C ++类背后的主要概念是,我们可以将事物的属性和事物的行为组合为一个单独的实体- 。 另一个基本概念是可以隐藏对象的属性,以便可以控制对那些属性的访问,以调节存储在对象中的数据。

An example of this is an employee’s age. Typically, we would store an age as an integer. However, the range of an integer in most C++ compiler’s can be from approximately -2 billion to +2 billion. So we can assign 1723 to a person’s age and by the rules of the compiler, this is a valid age. But of course it’s not, so we can regulate how a program interacts with the age property so that only legitimate ages can be entered for a person.

一个例子就是雇员的年龄。 通常,我们将年龄存储为整数。 但是,在大多数C ++编译器中,整数的范围可以从大约-20亿到+20亿。 因此,我们可以为一个人的年龄分配1723,根据编译器的规则,这是有效年龄。 但是当然不是,所以我们可以调节程序与年龄属性的交互方式,这样一个人只能输入合法年龄。

The ability to hide data in this way is part of the OOP concept of data encapsulation.

以这种方式隐藏数据的能力是数据封装的OOP概念的一部分。

Besides data, we can also use data encapsulation to hide the behaviors (member functions) of an object. For example, our payroll program will need to compute an employee’s net paycheck but we don’t want to expose this behavior to the user to exploit. So we can hide member functions so that they are not part of the interface that is accessible to users of the object. We can have a member function called calculatePayCheck, but it only calls another member function which is not part of the set of member functions callable from the object.

除了数据,我们还可以使用数据封装来隐藏对象的行为(成员函数)。 例如,我们的薪资程序将需要计算员工的净薪水,但我们不想将此行为暴露给用户以加以利用。 因此,我们可以隐藏成员函数,使它们不成为对象用户可访问的接口的一部分。 我们可以有一个成员函数叫做calculatePayCheck ,但是它仅调用另一个成员函数,该成员函数不是可从对象调用的成员函数集的一部分。

That’s enough high-level explanation for now. Let’s get down to nuts and bolts and learn how to create classes in C++.

到目前为止,这已经足够高层次的解释了。 让我们深入了解并学习如何在C ++中创建类。

建立课程 (Creating a Class)

I am going to demonstrate how to create a class by defining a class that keeps track of dates. The first thing you do when creating a class is give the class a name in the compiler’s global space:

我将演示如何通过定义跟踪日期的类来创建类。 创建类时,您要做的第一件事是在编译器的全局空间中为该类命名:

#include <iostream>
#include <vector>using namespace std;class Date {};int main ()
{ return 0;
}

Notice that the closing curly brace for the class definition has a semicolon after it. This is required and will cause an error message if it is left out.

请注意,类定义的右花括号后跟一个分号。 这是必需的,如果忽略该错误,则会导致错误消息。

The next step is to define the member variables that will store the data for the class. For a date, we want to store the month, the day, and the year, so these become our member variables. We want this data hidden from the user so we specify that by placing the member variable declarations inside a private access section, like this:

下一步是定义将存储该类数据的成员变量。 对于日期,我们要存储月,日和年,因此它们成为我们的成员变量。 我们希望向用户隐藏此数据,因此我们可以通过将成员变量声明放置在private访问部分中来进行指定,如下所示:

class Date {
private:
int month, day, year;};

Once you’ve determined the member variables, the next step is to create the member functions that make up the interface for the class. There are many different member functions we can define for a Date class, but for now let’s just define one that displays the date in standard month/day/year format.

确定成员变量后,下一步就是创建组成类接口的成员函数。 我们可以为Date类定义许多不同的成员函数,但是现在让我们定义一个以标准月/日/年格式显示日期的成员函数。

The member functions that are part of the interface users of our class can access are placed in the public section of the class definition. Functions can also be placed in the private section but these functions are not accessible by users of the class and are often called helper functions because they help other, public member functions do their job.

属于我们的类用户界面的一部分的成员函数位于类定义的public部分中。 函数也可以放在private部分中,但是此类用户不能被类的用户访问,并且通常被称为辅助函数,因为它们可以帮助其他public成员函数完成工作。

Here is the definition for a display member function:

这是display成员函数的定义:

class Date {
private:
int month, day, year;public:
void display() {
cout << month << "/" << day << "/" << year;
}
};

These are very simplified definitions and I will improve them in a future article.

这些是非常简化的定义,我将在以后的文章中对其进行改进。

Let’s see what the complete Date class definition looks like at this point:

让我们来看一下完整的Date类定义:

class Date {
private:
int month, day, year;public:
void display() {
cout << month << "/" << day << "/" << year;
} void setMonth(int m) {
month = m;
} void setDay(int d) {
day = d;
}

void setYear(int y) {
year = y;
}
};

There is a lot more I can do with this definition but for now let’s look at how we can use this Date class in a program.

我可以用这个定义做更多的事情,但是现在让我们看看如何在程序中使用这个Date类。

创建类对象 (Creating Class Objects)

Once you’ve defined your class, you’re ready to use it in a program. A class object is created using the same syntax you use to create a variable. Here is a syntax template for creating a class object:

一旦定义了类,就可以在程序中使用它了。 使用与创建变量相同的语法创建类对象。 这是用于创建类对象的语法模板:

class-name object-name(parameter-list);

类名对象名(参数列表);

The parameter list is used when you have one or more constructor functions defined for your class. I’ll cover constructors in my next article.

当您为类定义了一个或多个构造函数时,将使用参数列表。 我将在下一篇文章中介绍构造函数。

Here is how to create a Date class object:

以下是创建Date类对象的方法:

Date today;

The today object is now an instance of the Date class and the act of creating a new class object is called instantiation.

今天的对象现在是Date类的实例 ,创建一个新的类对象的动作称为实例化

The next step would be to add some data to the object using the member functions. Here is the code fragment that does that:

下一步将是使用成员函数将一些数据添加到对象。 这是执行此操作的代码片段:

today.setMonth(8);
today.setDay(23);
today.setYear(2020);

Now we can display the date we just set:

现在我们可以显示我们刚刚设置的日期:

today.display(); // displays 8/23/2020

Here is the complete program along with the class definition:

这是完整的程序以及类定义:

class Date {
private:
int month, day, year;public:
void display() {
cout << month << "/" << day << "/" << year;
} void setMonth(int m) {
month = m;
} void setDay(int d) {
day = d;
} void setYear(int y) {
year = y;
}
};int main ()
{
Date today;
today.setMonth(8);
today.setDay(23);
today.setYear(2020);
today.display();
return 0;
}

Here is the output from this program:

这是该程序的输出:

8/23/2020

I am not happy with the output because we want the format to by mm/dd/yyyy and the month is displaying just a single digit since the month number is less than 10. One way to solve this problem is to write a private function that checks to see how many digits its argument is and adjust the date digits accordingly.

我对输出不满意,因为我们希望格式为mm / dd / yyyy,并且由于月份数小于10,所以月份仅显示一位数字。解决此问题的一种方法是编写一个私有函数,检查其参数是多少位数,并相应地调整日期位数。

Here is one definition of such a function:

这是这种功能的一种定义:

string adjustDate(int d) {
string date;
if (d < 10) {
date = "0" + to_string(d);
}
else {
date = to_string(d);
}
return date;
}

Here is the new complete class definition:

这是新的完整类定义:

class Date {
private:
int month, day, year; string adjustDate(int d) {
string date;
if (d < 10) {
date = "0" + to_string(d);
}
else {
date = to_string(d);
}
return date;
}public:
void display() {
string date = adjustDate(month) + "/" + adjustDate(day)
+ "/" + adjustDate(year);
cout << date;
} void setMonth(int m) {
month = m;
} void setDay(int d) {
day = d;
} void setYear(int y) {
year = y;
}
};

Here is the output from this program:

这是该程序的输出:

08/23/2020

班级还有很多 (There’s So Much More to Classes)

This article is just a basic introduction to object-oriented programming in C++. For my next article, I’ll discuss how to create and use constructors, which make instantiating new class objects easier and more efficient because you can assign data to the member variables when you instantiate a new class object.

本文只是C ++中面向对象编程的基本介绍。 在我的下一篇文章中,我将讨论如何创建和使用构造函数,这些构造函数使实例化新的类对象更加容易和高效,因为在实例化新的类对象时可以将数据分配给成员变量。

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

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

翻译自: https://levelup.gitconnected.com/learning-c-an-introduction-to-classes-6abb3487e39b

c:foreach i++

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值