this指针

1620656678104

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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstring>

using namespace std;

class Student
{
public:
Student();
~Student();
Student(const char * name,int score);
//在成员函数后面加上const代表不能修改成员变量
const char * getName()const;
void print()const;
private:
char * name;
int score;
int xueHao;
static int jXueHao;
};
int Student::jXueHao = 10000;





//打印类成员
void Student::print() const
{
cout << name << endl;
cout << score << endl;
cout << xueHao << endl;
}



//返回name
const char * Student::getName()const
{
return this->name;
}

Student::Student(const char * name, int score)
{
int len = strlen(name) + 1;

this->name = new char[len];

strcpy(this->name, name);

this -> score = score;

xueHao = jXueHao + 1;
jXueHao++;

}

Student::Student()
{
name = NULL;
xueHao = jXueHao + 1;
jXueHao++;
}

Student::~Student()
{
if (name != NULL)
{
delete[] name;
name = NULL;
}
}

void test() {
Student s1("XiaoMing", 100);

s1.print();
cout << s1.getName() << endl;
}

int main(char *argv[], int argc)
{
test();

return 0;
}

1620656998746