C++中类(class)与结构(struct)其实是一样的,唯一不同点是类(class)的成员默认访问控制是私有的private,结构(struct)的成员默认访问控制是公有的public。
以下用Cpeople来举例说明类(class)与结构(struct),
用(class)类来定义Cpeople:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class Cpeople { //private: //如果这里不写私有的private,默认就是私有private string ID; string name; bool Gender; unsigned int height; unsigned int weight; protected: unsigned int age; public: static unsigned int Num; void SetID(string strI, bool gender = true); string GetID(); void PrintAdder() { cout<<"用this查看对象地址:"<<this<<endl; } }; |
用(struct)结构来定义Cpeople:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
struct Cpeople { //public: //如果这里不写私有的private,默认就是公有public string ID; string name; bool Gender; unsigned int height; unsigned int weight; protected: unsigned int age; public: static unsigned int Num; void SetID(string strI, bool gender = true); string GetID(); void PrintAdder() { cout<<"用this查看对象地址:"<<this<<endl; } }; |
从上面两段Cpeople类定义可以看出,类(class)与结构(struct)定义的差异 就是在默认访问类型。
为什么一个语言里会有两个关键字做同样的事?
这个就是说到C++的历史了。C++是从C发展过来的,完全兼容C的特性,所以也支持结构(struct),但C++又是面向对象的,所以(struct)也具有了面向对象功能。
但一般的人们在使用时还是会用(class)关键字来代表类,让(struct)结构来描述一些没有行为的,比如点、圆等等。