C,结构体和类,结构体和类的区别,struct与class的区别
C++,结构体和类,结构体和类的区别
结构体和类的唯一区别: 结构体和类具有不同的默认访问控制属性。
1、结构体中,未指定任何访问控制属性的成员,其访问控制属性为公有类型(public)。
2、类中,未指定任何访问控制属性的成员,其访问控制属性为公有类型(private)。代码案例
代码案例(结构体): #include using namespace std; struct Point { // 未指定任何访问控制属性的成员,其访问控制属性为公有类型(public) int x; int y; public: void setX(int x) { this->x = x; } void setY(int y) { this->y = y; } public: void out() { cout << x << "." << y << endl; } }; int main() { Point point1; point1.x = 55; point1.setY(55); point1.out(); cout << "大小:" << sizeof(point1) << endl; system("pause"); return 0; }
代码案例(类): #include using namespace std; // 类 class Point { // 未指定任何访问控制属性的成员,其访问控制属性为公有类型(private) int x=6; int y=6; public: void setX(int x) { this->x = x; } void setY(int y) { this->y = y; } public: void out(){ cout << "x" << "." << "y" << endl; } }; int main() { Point point1; point1.setX(66); point1.setY(66); point1.out(); cout << "大小:" << sizeof(point1) << endl; system("pause"); return 0; }