day04_类
类
-
C++中可以使用struct、class来定义一个类
-
struct和class的区别
- struct的默认成员权限是public
- class的默认成员权限是private
struct Person { int m_id; int m_age; int m_height; void display() { cout << "m_id = " << this->m_id << endl; cout << "m_age = " << this->m_age << endl; cout << "m_height = " << this->m_height << endl; } }; struct Person { int m_id; int m_age; int m_height; void display() { // this指向Person对象的指针 // this里面存储的就是Person对象的地址值 this->m_id = 5; this->m_age = 6; this->m_height = 7; /*cout << "m_id = " << this->m_id << endl; cout << "m_age = " << this->m_age << endl; cout << "m_height = " << this->m_height << endl;*/ } }; int main() { Person person; person.m_id = 10; person.m_age = 20; person.m_height = 30; Person *pPerson = (Person *)&person.m_age; pPerson->m_id = 40; pPerson->m_age = 50; person.display(); getchar(); return 0; }
C++****编程规范
- 全局变量:g_
- 成员变量:m_
- 静态变量:s_
- 常量:c_
- 使用驼峰标识
封装
成员变量私有化,提供公共的getter和setter给外界去访问成员变量
struct Person {
private:
int m_age;
public:
void setAge(int age) {
// 过滤
if (age < 0) return;
this->m_age = age;
}
int getAge() {
return this->m_age;
}
};
int main() {
Person person;
person.setAge(-20);
cout << person.getAge() << endl;
getchar();
return 0;
}