类和对象#
类型与变量#
类型 |
变量 |
int |
a |
long long |
b |
char |
c |
double |
d |
float |
e |
类型 = 类型数据 + 类型操作
类与对象#
类 |
对象 |
cat |
garfield |
dog |
odie |
people |
hug |
访问权限#
public |
公共访问权限 |
private |
私有访问权限 |
protected |
受保护的访问权限 |
成员属性与方法#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
#include <iostream>
using namespace std;
struct A {
int x, y;
void echo() {
cout << "hello world a" << endl;
return ;
}
};
struct B {
private:
int x, y;
public:
void set_xy(int x, int y) {
cout << this << endl;
this->x = x, this->y = y;
}
void echo() {
cout << "hello world b" << endl;
cout << x << " " << y << endl;
return ;
}
};
int main() {
A a;
B b;
a.x = 1, a.y = 2;
b.set_xy(3, 4);
cout << &b << endl;
cout << a.x << " " << a.y << endl;
b.echo();
return 0;
}
|
构造函数与析构函数#
构造/析构函数 |
使用方式 |
默认构造函数 |
People a; |
People(string name) |
People a(“hug”); |
People(const People &a) |
拷贝构造,与=不等价 |
~People(); |
无 |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
#include <iostream>
using namespace std;
struct A {
A() : next(nullptr) {
cout << this << " default constructor" << endl;
}
A(A *obj) {
this->next = obj;
this->next->arr = new int[1000];
}
A(int n) : next(nullptr) {
cout << this << " an int constructor" << endl;
x = n, y = n;
}
A(const A &obj) : next(nullptr) {
cout << this << " copy constructor" << endl;
this->x = obj.x, this->y = obj.y;
}
void output() {
cout << this->x << " " << this->y << endl;
}
int x, y;
int *arr;
A *next;
~A() {
if (this->next) {
delete this->next->arr;
}
cout << this << " destructor" << endl;
}
};
void func(int &x) {
x += 5;
}
A aa;
A bb(&aa);
A cc(&bb);
int main() {
int n = 7;
func(n);
cout << n << endl;
cout << "pre position" << endl;
A a;
A b = 8;
A c(a);
cout << "a = " << &a << endl;
cout << "b = " << &b << endl;
cout << "c = " << &c << endl;
cout << "aa = " << &aa << endl;
cout << "bb = " << &bb << endl;
cout << "cc = " << &cc << endl;
b.output();
b = 6;
b.output();
cout << "next position" << endl;
return 0;
}
|
类的构造函数#
类的构造函数是类的一种特殊的成员函数,它会在每次创建类的新对象时执行。
构造函数的名称与类的名称是完全相同的,并且不会返回任何类型,也不会返回 void。构造函数可用于为某些成员变量设置初始值。
类的析构函数#
类的析构函数是类的一种特殊的成员函数,它会在每次删除所创建的对象时执行。
析构函数的名称与类的名称是完全相同的,只是在前面加了个波浪号 (~) 作为前缀,它不会返回任何值,也不能带有任何参数。析构函数有助于在跳出程序(比如关闭文件、释放内存等)前释放资源。
https://www.runoob.com/cplusplus/cpp-constructor-destructor.html
结构体与类
struct 访问权限默认为 public
class 访问权限默认为 private