#include "stdafx.h" struct Test { int age; int level; //构造函数 Test(int age, int level) { this->age = age; this->level = level; } //重载构造函数 Test() { } //成员函数 void Print() { printf("%d %d",this->age,this->level); } }; int main(int argc, char* argv[]) { Test p(1,2); p.Print(); getchar(); return 0; }
#include "stdafx.h" #include "malloc.h" struct Person { int age; int level; char* arr; Person(int age,int level) { printf("有参构造函数执行了...\n"); this->age = age; this->level = level; arr = (char*)malloc(1024); } ~Person() { printf("析构函数执行了..."); free(arr); arr = NULL; } void Print() { printf("%d-%d\n",age,level); } }; void Test() { Person p(1,2); p.Print(); } int main(int argc, char* argv[]) { Test(); getchar(); return 0; }
#include "stdafx.h" struct Person { int age; int sex; }; struct Teacher:Person { int level; int classId; }; struct Student:Person { int code; int score; }; void Test() { Student t; t.age = 1; t.sex = 2; t.code = 3; t.score = 4; Person* pt = &t; printf("%d\n",pt->age); } int main(int argc, char* argv[]) { Test(); getchar(); return 0; }
不推荐写法
#include "stdafx.h" struct X { int a; int b; }; struct Y:X { int a; int d; }; struct Z:Y { int e; int f; }; void Test() { Z z; z.X::a = 1; z.b = 2; z.Y::a = 3; z.d = 4; z.e = 5; z.f = 6; printf("%d\n",sizeof(z)); } int main(int argc, char* argv[]) { Test(); getchar(); return 0; }
不推荐写法
#include "stdafx.h" struct X { int a; int b; }; struct Y { int a; int d; }; struct Z:X,Y { int e; int f; }; void Test() { Z z; z.X::a = 1; z.b = 2; z.Y::a = 3; z.d = 4; z.e = 5; z.f = 6; printf("%d\n",sizeof(z)); } int main(int argc, char* argv[]) { Test(); getchar(); return 0; }
不能编译,因为私有属性不能直接调用,需要在结构体内调用
#include "stdafx.h" struct Test { private: int x; public: int y; }; int main(int argc, char* argv[]) { Test p; p.x = 10; return 0; }
private修饰的成员与普通的成员没有区别 只是编译器会检测.
private修饰的成员只要自己的其他成员才能访问
#include "stdafx.h" struct Test { private: int x; public: int y; void Init(int x,int y) { this->x = x; this->y = y; } }; int main(int argc, char* argv[]) { Test t; t.Init(1,2); int* p = (int*)&t; int n = *p; int m = *(p+1); printf("%d %d\n",n,m); getchar(); return 0; }
继承,相当于将父类的属性复制一份,但是编译器不允许我们使用私有的,但我们可以通过指针来调用
#include "stdafx.h" class Base { public: Base() { x = 11; y = 12; } private: int x; int y; }; class Sub:Base { public: int a; int b; }; int main(int argc, char* argv[]) { Sub sub; sub.a = 1; sub.b = 2; int* p = (int*)⊂ printf("%d\n",sizeof(sub)); printf("%d\n",*(p+0)); printf("%d\n",*(p+1)); printf("%d\n",*(p+2)); printf("%d\n",*(p+3)); getchar(); return 0; }