C++|带参数的构造函数

基础语法而已。

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
62
63
64
65
66
67
68
69
70
#include <iostream>
using namespace std;

class Demo
{
public:
Demo()
{
x = 0;
cout << "Demo 的默认构造函数!" << x << endl;
}
Demo(int i)
{
x = i;
cout << "Demo 的带一个参数的构造函数!!" << x << endl;
}
~Demo()
{
cout << "Demo 的析构函数!" << x << endl;

}
int get_x()
{
return x;
}
void set_x(int i)
{
x = i;
}
private:
int x;
};

class Rectangle
{
public:
Rectangle()
{
x = 1000;
cout << "Rectangle 的默认构造函数!" << x << endl;
}
Rectangle(int i, int j, int k):x(i), width(j), length(k)
{
cout << "Rectangle 的带三个参数的构造函数!" << "长方形的面积 b 为:" << length.get_x() * width.get_x() << endl;
}
~Rectangle()
{
cout << "Rectangle 的默认析构函数!" << x << endl;
}
int area()
{
return length.get_x() * width.get_x();
}
private:
Demo length;
Demo width;
int x;
};

int main()
{
Rectangle rec(100, 200, 300);

cout << "\n=========\n" << endl;

Rectangle *rec1 = new Rectangle(100, 200, 300);
delete rec1;

return 0;
}

输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Demo 的带一个参数的构造函数!!300
Demo 的带一个参数的构造函数!!200
Rectangle 的带三个参数的构造函数!长方形的面积 b 为:60000

=========

Demo 的带一个参数的构造函数!!300
Demo 的带一个参数的构造函数!!200
Rectangle 的带三个参数的构造函数!长方形的面积 b 为:60000
Rectangle 的默认析构函数!100
Demo 的析构函数!200
Demo 的析构函数!300
Rectangle 的默认析构函数!100
Demo 的析构函数!200
Demo 的析构函数!300

参考:《范磊:C++》P153
感谢支持!