赞
踩
目录
前言
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 << s.Top() << endl;
- s.Destroy();
- return 0;
- }

语法规则:
- class className
- {
- // 类体:由成员函数和成员变量组成
- }; // 一定要注意后面的分号
2.类声明放在.h文件中,成员函数定义放在.cpp文件中,注意:成员函数名前需要加类名::
为了与其他变量区分开,成员变量的命名前一般加一个“_”
- class Person
- {
- public:
- void PrintPersonInfo();
- private:
- char _name[20];
- char _gender[3];
- int _age;
- };
- // 这里需要指定PrintPersonInfo是属于Person这个类域
- void Person::PrintPersonInfo()
- {
- cout << _name << " "<< _gender << " " << _age << endl;
- }
相当于在Person查找函数的声明,跟之前命名空间类似。
- int main()
- {
- Person._age = 100; // 编译失败:error C2059: 语法错误:“.”
- return 0;
- }
3.类实例化出对象就像现实中使用建筑设计图建造出房子,类就像是设计图,只设 计出需要什么东西,但是并没有实体的建筑存在,同样类也只是一个设计,实例化出的对象 才能实际存储数据,占用物理空间
我们可以通过sizeof来计算类的大小
- class A
- {
- public:
- void PrintA()
- {
- cout<<_a<<endl;
- }
- private:
- char _a;
- };
-
- int main(){
- A.st
-
- cout<<sizeof(st)<<endl; //4
- cout<<sizeof(A)<<endl; //4
-
- }

我们发现类的大小只计算了成员变量的大小,没计算成员函数的大小,因为类对象的存储方式为只保存成员变量,成员函数存放在公共的代码段
- class Date
- {
- public:
- void Init(int year, int month, int day)
- {
- _year = year;
- _month = month;
- _day = day;
- }
- void Print()
- {
- cout <<_year<< "-" <<_month << "-"<< _day <<endl;
- }
- private:
- int _year; // 年
- int _month; // 月
- int _day; // 日
- };
- int main()
- {
- Date d1, d2;
- d1.Init(2022,1,11);
- d2.Init(2022, 1, 12);
- d1.Print();
- d2.Print();
- return 0;
- }

特性:
我们来看下面两段代码:
- // 1.下面程序编译运行结果是? A、编译报错 B、运行崩溃 C、正常运行
- class A
- {
- public:
- void Print()
- {
- cout << "Print()" << endl;
- }
- private:
- int _a;
- };
- int main()
- {
- A* p = nullptr;
- p->Print();
- return 0;
- }
- // 1.下面程序编译运行结果是? A、编译报错 B、运行崩溃 C、正常运行
- class A
- {
- public:
- void PrintA()
- {
- cout<<_a<<endl;
- }
- private:
- int _a;
- };
- int main()
- {
- A* p = nullptr;
- p->PrintA();
- return 0;
- }

1.代码正常运行,p为空指针,但是是直接调用代码段上的Print(),没有对p进行引用。
2.运行崩溃,p为空指针,即传过去的this指针为空,再this._a对空指针的引用则会崩溃。
总结
以上就是C++中类和对象的一部分内容,希望对你有所帮助。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。