参考:https://blog.csdn.net/w616358337/article/details/47302515
https://www.cnblogs.com/dwdxdy/archive/2012/07/17/2595741.html
1 #include <string>
2 #include <iostream>
3 using namespace std;
4 #pragma once
5 namespace pan{//命名空间
6 class Person
7 {
8 friend void ff();
9 private:
10 string name;
11 string age;
12 static int count1;//static类变量
13 string* gname;//girlfirend name
14
15 public:
16 const string getAge();
17 void setAge(string age);
18
19 string getName();
20 string getgName();
21 void setgName(string s);
22
23 Person(void);
24 Person(string age,string name,string gname);
25 Person(const Person& p);//拷贝构造函数
26 virtual ~Person(void);
27
28 void test(Person p);
29 Person& operator=(const Person& p);
30 static int getcount();//静态函数
31 };
32 }
33
34 using namespace pan;
35
36 int Person::count1=0;//static类变量初始化 需要在CPP初始化 需要加类型 int
37
38 void Person::setAge(string age)
39 {
40 this->age=age;
41 }
42 const string Person::getAge()
43 {
44 return this->age;
45 }
46
47 string Person::getName()
48 {
49 return this->name;
50 }
51 void Person::setgName(string s)
52 {
53 gname=new string;
54 (*gname)=s;
55 }
56
57 int Person::getcount()
58 {
59 return count1;
60 }
61
62 Person::Person(void):gname(NULL),name(""),age("")
63 {
64 Person::count1++;
65 }
66
67 string Person::getgName()
68 {
69 return *(gname);
70 }
71
72 Person& Person::operator=(const Person& p)//重载运算符=
73 {
74 this->age=p.age;
75 this->name=p.name;
76
77 if(this->gname==NULL) {
78 this->gname=new string;
79 }
80 if(&p!=this) {
81 *(this->gname)=*(p.gname);
82 }
83 return *this;
84 }
85
86 void Person::test(Person p)
87 {
88 cout<<*(p.gname)<<"www";
89 }
90
91 Person::Person(string age,string name,string gname):age(age),name(name)
92 {
93 this->gname=new string;
94 *(this->gname)=gname;
95 }
96
97 Person::Person(const Person& p)//拷贝构造函数
98 {
99 this->age=p.age;
100 this->name=p.name;
101 this->gname=new string;
102 *(this->gname)=*(p.gname);
103 }
104
105 Person::~Person(void)
106 {
107 delete gname;
108 }
109
110 //测试代码
111 int main(void)
112 {
113 pan::Person p1,p2;
114 p1.setAge("aaaa");
115 p1.setgName("liujing");
116 p2=p1;//重载=运算符
117 cout<<p2.getgName()<<endl;
118 p2.setgName("eeee");
119 cout<<p2.getgName()<<endl;
120 cout<<p1.getgName()<<endl;
121 Person p3(p2);//拷贝构造
122 cout<<p3.getgName()<<endl;
123 cout<<Person::getcount()<<endl;//访问静态成员函数
124
125 return 0;
126 }