【编程学习】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
#include <iostream>

using namespace std;

class Dog
{
public:
double dog_weight;
int dog_age;
string dog_name;

Dog(string name);
void run(void);
void set(double weight, int age);
private:
double something;
};

//类的构造函数
Dog::Dog(string name)
{
cout << "Dog is being created" << endl;
dog_name = name;
}
/*
简化方案:
Dog::Dog(string name): dog_name(name)
{
cout << "Dog is being created" << endl;
}
*/

//类的解析函数
Dog::~Dog(void)
{
cout << "Dog is being deleted" << endl;
}

// 构建类方法的具体实现
void Dog::set(double weight, int age)
{
dog_weight = weight;
dog_age = age;
}

void Dog::run(void)
{
cout << "The dog " + dog_name + " is running!" << endl;
}

// 主函数
int main()
{
Dog dog1("Mark");
dog1.set(5.6, 3);
cout << "The name of dog1 is " << dog1.dog_name << endl;
cout << "The weight of dog1 is " << dog1.dog_weight << endl;
cout << "The age of dog1 is " << dog1.dog_age << endl;
dog1.run();

return 0;
}

其实也不用过多的讲解,触类旁通。