classes and objects in C++ - C++ 中的类和对象

classes and objects in C++ - C++ 中的类和对象

1. classes and objects in C++

In this section, you will learn to make our own class.

//============================================================================
// Name        : std::class
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>

using namespace std;

class Rectangle
{
public:
	int length;         //length of rectangle
	int breadth;        //breadth of rectangle

	/* declaring member functions */
	void setLength(int l);
	void setBreadth(int b);
	int getArea();
};

/* defining member functions */
void Rectangle::setLength(int l)
{
	length = l;
}

void Rectangle::setBreadth(int b)
{
	breadth = b;
}

int Rectangle::getArea()
{
	return length * breadth;
}

int main()
{
	Rectangle rt;

	rt.setLength(7);
	rt.setBreadth(4);

	int area = rt.getArea();
	cout << "Area : " << area << endl;

	return 0;
}

Output

Area : 28

Remember that the execution of any program begins with the main function. So while executing, the first statement of the main function will get executed first.
请记住,任何程序的执行都是从 main 函数开始的。因此,在执行时,将首先执行 main 函数的第一条语句。

Rectangle rt; - This statement declares rt as an object of class Rectangle. It is the same as saying that rt is a Rectangle. For this, Rectangle must be defined.
Rectangle rt; - 此语句将 rt 声明为 Rectangle 类的对象。就像说 rtRectangle 一样。为此,必须定义 Rectangle

class Rectangle - We have defined our own class named Rectangle. class is a keyword which means that Rectangle is a class.
class Rectangle - 我们定义了自己的名为 Rectangle 类。class 是关键字,表示 Rectangle 是一个类。

Inside the Rectangle class, we declared two variables and three functions. These variables and functions belong to the class Rectangle since these are declared inside the class and thus are called members of the class. There are two types of members of a class:
Rectangle 类内部,我们声明了两个变量和三个函数。这些变量和函数属于 Rectangle 类,因为它们是在类内部声明的,因此被称为类的成员。类的成员有两种类型:

  • data members - In the class Rectangle, length and breadth are the data members since these store the information (length and breadth) of the objects of the class.
    data members - 在 Rectangle 类中,length and breadth 是数据成员,因为它们存储了该类对象的信息 (length and breadth)。

  • member functions - setLength(), setBreadth and getArea() are the member functions of the Rectangle class.
    member functions - setLength(), setBreadth and getArea()Rectangle 类的成员函数。

Note that while defining the member functions, we have written Rectangle:: before the function name. This is to tell the compiler that the function belongs to the class Rectangle.
请注意,在定义成员函数时,我们在函数名称之前编写了 Rectangle::。这是告诉编译器该函数属于类 Rectangle

rt.setLength(7); - This statement will call the function setLength with the parameter value 7. To call any function, we use (.) DOT after the object and then call that function.
rt.setLength(7); - 此语句将调用参数值为 7 的 setLength 函数。要调用任何函数,我们在对象后使用 (.) DOT,然后调用该函数。

Since rt is an object of the Rectangle class, so rt.setLength will call the function setLength of Rectangle class for rt. This will set the value of length as 7 for rt.
因为 rtRectangle 类的对象,所以 rt.setLength 将为 rt 调用 Rectangle 类的 setLength 函数。这会将 rtlength 值设置为7。

Similarly, rt.setBreadth(4) will call the function setBreadth and will set the value of breadth as 4.
同样,rt.setBreadth(4) 将调用函数 setBreadth 并将 breadth 的值设置为 4。

int area = rt.getArea(); - rt will call the function getArea() which will return length * breadth which is 28 (since the value of length is 7 and that of breadth is 4). This value will get assigned to the variable area.
int area = rt.getArea(); - rt 将调用函数 getArea(),该函数将返回 length * breadth 为 28 (因为 length 的值为 7,而 breadth 的值为是 4)。该值将分配给变量 area

public: - We declared all the members of the class as public. public is a modifier which allows the members of a class to be accessed directly from outside the class.
public: - 我们声明该类的所有成员为 publicpublic 是一个修饰符,它允许从类外部直接访问类的成员。

Like public, there are other modifiers also like private and protected. We will study more about modifier later.
public 一样,还有其他修饰符,例如 private and protected。稍后我们将详细研究修饰符。

We can also define our member methods at the time it is declared in the function as in the following example.
我们还可以在函数中声明成员方法时定义其成员方法,如以下示例所示。

//============================================================================
// Name        : std::class
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>

using namespace std;

class Rectangle
{
public:
	int length;         //length of rectangle
	int breadth;        //breadth of rectangle

	/* declaring member functions */
	void setLength(int l)
	{
		length = l;
	}

	void setBreadth(int b)
	{
		breadth = b;
	}

	int getArea()
	{
		return length * breadth;
	}
};

int main()
{
	Rectangle rt;

	rt.setLength(7);
	rt.setBreadth(4);

	int area = rt.getArea();
	cout << "Area : " << area << endl;

	return 0;
}

Output

Area : 28

This was the same as the previous example but this time we defined the function at the time we declared it in the Rectangle class.
这与前面的示例相同,但是这次我们在 Rectangle 类中声明函数时定义了该函数。

2. Access Modifiers

The access modifiers decide how the members of a class can be accessed. There are three types of access modifiers in C++.
访问修饰符决定如何访问类的成员。C++ 中有三种访问修饰符。

  • public
  • private
  • protected

2.1 Public

When we declare any class member as public, that variable becomes available everywhere in the program, even outside the function in which it was declared. Let’s see an example to understand this.
当我们将任何类成员声明为 public 时,该变量在程序中的任何地方都可用,即使在声明它的函数之外也是如此。让我们看一个例子来理解这一点。

//============================================================================
// Name        : std::class
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>

using namespace std;

class Rectangle
{
public:
	int length;         //length of rectangle
	int breadth;        //breadth of rectangle
	int getArea()
	{
		return length * breadth;
	}
};

int main()
{
	Rectangle rt;

	rt.length = 7;
	rt.breadth = 4;

	int area = rt.getArea();
	cout << "Area : " << area << endl;

	return 0;
}

Output

Area : 28

Since we declared the variables length and breadth as public, we directly accessed these and assigned them values.
由于我们将变量 length and breadth 声明为 public,因此我们直接访问它们并为其分配值。

  • rt.length = 7; - We directly accessed the data member length by the object of the Rectangle class. Similarly, we assigned breadth to the Rectangle object by directly accessing it.
    rt.length = 7; - 我们直接通过 Rectangle 类的对象访问数据成员 length。类似地,我们通过直接访问对象来将 breadth 分配给 Rectangle 对象。

  • rt.getArea(); - We also accessed getArea() directly since it is also declared as public.
    rt.getArea(); - 我们也直接访问了 getArea(),因为它也被声明为 public

Thus we can access the members declared as public from anywhere.
因此,我们可以从任何地方访问声明为 public 的成员。

2.2 Private

The member declared as private can only be accessed inside the class in which it is declared. Thus, the object of the class cannot directly access its members as we did in the case of public.
声明为 private 的成员只能在声明该类的类内部访问。因此,类的对象不能像在 public 的情况下那样直接访问其成员。

By default, all the members of a class are private.
默认情况下,一个类的所有成员都是 private

If we try to access a private member of any class from outside that class, we will get a compile time error.
如果我们尝试从该类外部访问任何类的 private 成员,则会收到编译时错误。

//============================================================================
// Name        : std::class
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>

using namespace std;

class Rectangle
{
	int length;

public:
	int breadth;
	void setLength(int l);
	int getArea();
};

void Rectangle::setLength(int l)
{
	length = l;
}

int Rectangle::getArea()
{
	return length * breadth;
}

int main()
{
	Rectangle rt;

	rt.setLength(7);
	rt.breadth = 4;
	int area = rt.getArea();
	cout << "Area : " << area << endl;

	return 0;
}

Output

Area : 28

In this example, breadth and the functions setLength and getArea are declared public. The data member length is private since all the members are private by default.
在这个例子中,breadth 和函数 setLengthgetArea 被声明为 public。由于默认情况下所有成员均为 private,因此数据成员的长度为 private

Since we cannot directly access any private member, therefore cannot access length directly. So, we declared another member function setLength as public which assigned a value 7 to the length.
由于我们不能直接访问任何 private 成员,因此不能直接访问 length。因此,我们将另一个成员函数 setLength 声明为 public,它为 length 分配了值 7。

The rest of the members were directly accessed from the main function.
其余的成员可以直接从 main 函数访问。

Though the data member length is by default private, we can declare it private as well as shown below.
尽管数据成员 length 默认为 private,但我们可以声明为 private,如下所示。

//============================================================================
// Name        : std::class
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

class Rectangle
{
private:
	int length;

public:
	int breadth;
	void setLength(int l);
	int getArea();
};

2.3 Protected

protected is similar to private. Any member declared as protected cannot be accessed outside the class but can be accessed by any subclass of that class.
protected 类似于 private。任何声明为 protected 的成员都不能在 class 之外访问,但是可以由该 class 的任何 subclass 访问。

3. Constructor

A constructor is a special member function of a class which is called automatically when an object of that class is called. It has the same name as that of the class and has no return type.
构造函数class 的特殊成员函数,当调用该 class 的对象时会自动调用该函数。它与 class 的名字相同,并且没有返回类型。

Constructor is a special type of function which is used to initialize an object. It is invoked at the time of object creation.
构造函数是一种特殊的函数,用于初始化对象。在创建对象时调用它。

//============================================================================
// Name        : std::class
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>

using namespace std;

class Rectangle
{
public:
	int length;
	int breadth;

	Rectangle()
	{
		length = 10;
		breadth = 10;
	}
};

int main()
{
	Rectangle rt;
	cout << "length = " << rt.length << endl;
	cout << "breadth = " << rt.breadth << endl;

	return 0;
}

Output

length = 10
breadth = 10

In this example when we created the object rt of class Rectangle, the constructor Rectangle() automatically got called and initialized the data members for the object rt. It initialized the length and breadth of rt to 10 each.
在此示例中,当我们创建类 Rectangle 的对象 rt 时,将自动调用构造函数 Rectangle() 并初始化对象 rt 的数据成员。它将 rtlength and breadth 初始化为10。

When the constructor was called, length and breadth were created and then in the body of the constructor, these member variables were assigned values.
调用构造函数时,将创建 length and breadth,然后在构造函数的主体中为这些成员变量分配值。

We can also make a constructor with nothing in its body.
我们还可以使构造函数本身不包含任何内容。

Rectangle(){ };

3.1 Constructor having Parameters

We can also have constructors with parameters.
我们也可以使用带参数的构造函数。

//============================================================================
// Name        : std::class
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>

using namespace std;

class Rectangle
{
	int length;
	int breadth;

public:
	Rectangle(int l, int b)
	{
		length = l;
		breadth = b;
	}

	int getArea()
	{
		return length * breadth;
	}
};

int main()
{
	Rectangle rt(7, 4);
	cout << "Area : " << rt.getArea() << endl;

	return 0;
}

Output

Area : 28

In this example, we have parameters in our constructor. As told earlier, a constructor is also a function which is executed at the time of creating an object and has the same name as that of its parent class. So, it will work like a function and assign values passed from Rectangle rt( 7, 4 ); to length and breadth.
在此示例中,构造函数中有参数。如前所述,构造函数也是在创建对象时执行的函数,其名称与其父类的名称相同。因此,它将像一个函数一样工作,并将从 Rectangle rt( 7, 4 ); 传递的值分配给 length and breadth

Rectangle rt( 7, 4 );

It will create an object rt of class Rectangle and pass 7 to l and 4 to b ( l and b are used in the constructor of the class Rectangle).
它将创建类 Rectangle 的对象 rt,并将 7 传递给 l,将 4 传递给 b (在 Rectangle 类的构造函数中使用 l and b)。

在这里插入图片描述

4. Use of static

static is used to make access to any data variable or function without making an object of that class. It means that static is used so that we can access any data variable or function without making an object of that class.
static 用于访问任何数据变量或函数,而无需创建该类的对象。这意味着使用 static,以便我们可以访问任何数据变量或函数而无需创建该类的对象。

//============================================================================
// Name        : std::class
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>

using namespace std;

class Rectangle
{
public:
	static void printArea(int l, int b)
	{
		cout << l * b << endl;
	}
};

int main()
{
	Rectangle::printArea(4, 7);

	return 0;
}

Output

28

Our function printArea is static. So, we directly used it on Rectangle class, without making any object of it.
我们的函数 printArea 是静态的。因此,我们直接在 Rectangle 类上使用了它,而没有使其成为任何对象。

Note that for calling a member function by the class itself, we have to use :: in place of the Dot (.).
请注意,要通过类本身调用成员函数,我们必须使用 :: 代替点 (.)。

In this example, we made a member function static. Now let’s see another example in which a data member is made static.
在这个例子中,我们使成员函数为 static。现在,让我们来看另一个示例,其中将数据成员设置为 static

//============================================================================
// Name        : std::class
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>

using namespace std;

class A
{
public:
	static int a;
};

int A::a = 8;

int main()
{
	cout << A::a << endl;

	return 0;
}


Output

8

Here, the variable a is made static and thus we directly accessed it in the main function.
在这里,变量 a 被设为 static,因此我们直接在 main 函数中对其进行了访问。

5. Returning and passing object in a function

Yes, we can return or pass object(s) to a function. Let’s see an example.
是的,我们可以将对象返回或传递给函数。让我们来看一个例子。

//============================================================================
// Name        : std::class
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>

class Account
{
public:
	int balance;

public:
	Account()
	{
		balance = 0;
	}

public:
	static Account getAcc(Account a, Account b)
	{
		Account ac;
		ac.balance = a.balance + b.balance;
		return ac;
	}
};
int main()
{
	using namespace std;

	Account a1;
	a1.balance = 50;

	Account a2;
	a2.balance = 60;

	Account b = Account::getAcc(a1, a2);
	cout << b.balance << endl;

	return 0;
}

Output

110

As you have seen, our method getAcc is creating an Account object by taking two Account objects and returning it also.
如您所见,我们的方法 getAcc 通过获取两个 Account 对象并返回它来创建 Account 对象。

Account b = Account::getAcc(a1, a2); - getAcc will create and return a new Account object and b will become equal to that object.
Account b = Account::getAcc(a1, a2); - getAcc 将创建并返回一个新的 Account 对象,b 将等于该对象。

Here, we have directly used getAcc method on class Account ( Account b = Account::getAcc(a1, a2); ) because getAcc is a static method ( static Account getAcc(Account a, Account b) ).
这里,我们直接在类 Account (Account b = Account::getAcc(a1, a2);) 上使用了 getAcc 方法,因为 getAcc 是一种静态方法 ( static Account getAcc(Account a, Account b) )。

If there is no constructor in a class, compiler automatically creates a default public constructor.
如果 class 中没有构造函数,编译器会自动创建一个默认的 public 构造函数。

Even if we don’t declare any constructor for a class, the compiler automatically declares a constructor which gets called when any object of that class is created and initializes its data members.
即使我们没有为类声明任何构造函数,编译器也会自动声明一个构造函数,该构造函数在创建该类的任何对象并初始化其数据成员时会被调用。

Suppose we made a class Vehicle without any constructor, then automatically its constructor will be created with nothing in its body as follows.
假设我们创建了一个不带有任何构造函数的 Vehicle 类,然后将自动创建其构造函数,其主体中不包含任何内容,如下所示。

//============================================================================
// Name        : std::class
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

class Vehicle
{
public:
	Vehicle()
	{
	}
}

Talent is good, practice is better, passion is best. - Frank Lloyd Wright (弗兰克·劳埃德·赖特)

inheritance [ɪnˈherɪtəns]:n. 继承,遗传,遗产
class:类
derived class:继承类,派生类
subclass:子类
base class:基类
superclass:超类,父类
passion [ˈpæʃn]:n. 激情,热情,酷爱,盛怒

References

https://www.codesdope.com/cpp-classes-and-objects/

发布了454 篇原创文章 · 获赞 1733 · 访问量 103万+

猜你喜欢

转载自blog.csdn.net/chengyq116/article/details/104402229