c++ class 类

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 class STU_INFO
 6 {
 7   private:
 8     string name = "unknown";
 9     string sex = "unknown";
10     int age = -1;
11     
12   public:
13     void setName(string);
14     void setSex(string);
15     void setAge(int);
16     void log();
17 };
18 
19 void STU_INFO::setName(string _name)
20 {
21     // 直接通过变量名赋值
22     name = _name;
23 }
24 
25 void STU_INFO::setSex(string _sex)
26 {
27     // 显式通过this指针访问变量
28     this->sex = _sex;
29 }
30 
31 void STU_INFO::setAge(int _age)
32 {
33     // 通过圆点运算符访问
34     (*this).age = _age;
35 }
36 
37 void STU_INFO::log()
38 {
39     cout << ("=========================") << endl;
40     cout << ("name:\t") << ((*this).name) << endl;
41     cout << ("sex:\t") << (sex) << endl;
42     cout << ("age:\t") << (this->age) << endl;
43 }
44 
45 int main()
46 {
47     // 创建对象
48     STU_INFO students;
49 
50     // 未赋值,打印默认值
51     students.log();
52 
53     // 设置新值并打印
54     students.setName("Fan");
55     students.setSex("");
56     students.setAge(29);
57     students.log();
58 
59     // 设置新值并打印
60     students.setName("Ye_er");
61     students.setSex("");
62     students.setAge(30);
63     students.log();
64     
65     return 0;
66 }

猜你喜欢

转载自www.cnblogs.com/zhangfan2014/p/10288864.html