hello朋友们,这里是勇子.虽说已经注册账号1年了,但真正踏上博客之路还是在这几天,我会把博客的内容做的尽可能的易懂,清晰。
OK,话不多说今天我来学习C++中的类与对象1。
文章目录
- 1.类的引入
- 2.类的定义
- 3.类的访问限定符
- 4.类访问限定符
- 5.类的实例化
- 6.类对象大小的计算
- 7.结构体内存对齐规则
- 面试题:
- 8.this指针
- this指针特性
1.类的引入
C语言结构体中只能定义变量,在C++中,结构体内不仅可以定义变量, 也可以定义函数。比如:之前在数据结构初阶中,用C语言方式实现的栈, 结构体中只能定义变量;现在以C++方式实现,会发现struct中也可以定义函数。
typedef int DataType; struct Stack { void Init(size_t capacity) { _array = (DataType*)malloc(sizeof(DataType) * capacity); if (nullptr == _array) { perror("malloc申请空间失败"); return; } _capacity = capacity; _size = 0; } void Push(const DataType& data) { // 扩容 _array[_size] = data; ++_size; } DataType Top() { return _array[_size - 1]; } void Destroy() { if (_array) { free(_array); _array = nullptr; _capacity = 0; _size = 0; } } DataType* _array; size_t _capacity; size_t _size; }; int main() { Stack s; s.Init(10); s.Push(1); s.Push(2); s.Push(3); cout // 类体:由成员函数和成员变量组成 }; // 一定要注意后面的分号 public: void showInfo() { cout public: void showInfo(); public: char* _name; char* _sex; int _age; }; //定义放在类的视线文件person.cpp文件中 #include cout public: void Init(int year) { _year = year; } private: int _year; }; // 或者这样 class Date { public: void Init(int year) { mYear = year; } private: int mYear; }; public: void PrintPersonInfo(); private: char _name[20]; char _gender[3]; int _age; }; // 这里需要指定PrintPersonInfo是属于Person这个类域 void Person::PrintPersonInfo() { cout Person._age = 100; // 编译失败:error C2059: 语法错误:“.” return 0; } public: void showInfo(); public: char* _name; char* _sex; int _age; }; void Test() { Person man; man._name="jack"; man._age=10; //要先实例化出一个 man;然后这个实例化的对象才占空间, //才有name,age,sex; ...... } }; int main() { cout public: 常规函数(非静态成员函数) void printHello() { cout cout public: A(int x=0) { cout cout public: B(int x=0) { cout cout public: C(int x=0) { cout cout A a; B b; C c; cout public: static int staticVar; // 静态成员变量,加了static }; int StaticMemberClass::staticVar = 0; // 静态成员变量的定义 int main() { cout int a; char b; } __attribute__((aligned(4))); int a = 1; int num = (*(char*)&a);//&a 取出a的地址; (char*)&a 代表a变量地址的第一个字节的地址 printf("%d\n", num);//(*(char*)&a) 解引用取出第一个字节保存的内容 if (num == 1) printf("小端\n"); else printf("大端\n"); } int main() { CheckSystem1(); getchar(); return 0; } //2.联合体特性 int CheckSystem2() { union check { int num; char a;//2个变量公用一块内存空间,并且2个变量的首地址相等 }b; b.num = 1;//1存放在变量num的低位 return (b.a == 1);//当变量a=1,相当于将数据的低位存到了内存的低地址处,即小端模式 } int main() { int c = CheckSystem2(); printf("c : %d\n", c); getchar(); return 0; } public: void Init(int year, int month, int day) { _year = year;//this-_year=year; _month = month; _day = day; } // 不能显示的写实参和形参 // void Print(Date* const this) void Print() { //this = nullptr; cout Date d1; d1.Init(2023, 10, 19); //编辑器视角下是 d1.Init(&d1,2023,10,19) //这里,&d1是d1对象的地址,它会被隐式地作为 this 指针传递给 Init 函数。然后,在 init 函数内部,编译器会像这样使用 this 指针: // 初始化函数里面 //this-_year=year; Date d2; d1.Print(); // d1.Print(&d1); d2.Print(); return 0; }
- this指针特性