(9)C++ 对象和类
2024-10-07 17:29:29
一、类
1.访问控制
class student {
int age;//默认私有控制
public:
string name;
double weight;
};
2.成员函数
- 定义成员函数时,使用::标识函数所属的类
- 类方法可以访问类的private组件
成员函数声明与普通函数相同,定义时分类外定义和类内定义
类内定义,在类中声明的函数都是默认都是内联函数(加上inline)
#include<iostream>
using namespace std;
class student {
public:
int sum(int a, int b) {
return a + b;
}
}; void main() {
student stu;//创建对象
int a=stu.sum(, );
cout << a << endl;
}
类外定义
#include<iostream>
using namespace std;
class student {
public:
int sum(int a,int b);//函数声明
}; inline int student::sum(int a, int b) {//类外定义
return a + b;
} void main() {
student stu;//创建对象
int a=stu.sum(, );
cout << a << endl;
}
再强调下内联函数的作用:内联函数和普通函数的区别在于:当编译器处理调用内联函数的语句时,不会将该语句编译成函数调用的指令,而是直接将整个函数体的代码插人调用语句处,就像整个函数体在调用处被重写了一遍一样。有了内联函数,就能像调用一个函数那样方便地重复使用一段代码,而不需要付出执行函数调用的额外开销。很显然,使用内联函数会使最终可执行程序的体积增加。以时间换取空间,或增加空间消耗来节省时间,这是计算机学科中常用的方法 。
二、构造函数和析构函数
1.构造函数
为了隐藏数据,并且在创建时进行初始化,创造了构造函数的功能.
(1)使用带参构造函数
#include<iostream>
using namespace std;
class student {
int m_a = ;
int m_b = ;
public:
student() { }//默认构造函数
student(int a, int b) {
m_a = a;
m_b = b;
}//带参构造函数
int sum() {
return m_a + m_b;
};
}; void main() {
student stu1 = student{,};//1.显示调用构造函数
int a1 = stu1.sum();
cout <<"显示调用构造函数 "<< a1 << endl; student stu2 ( , );//2.隐式调用构造函数
int a2= stu2.sum();
cout << "隐式调用构造函数 " << a2 << endl; student *stu3 = new student(, );//3.动态调用构造函数
int a3=stu3->sum();
cout << "动态调用构造函数 " << a3 << endl;
}
(2)默认构造函数
class student {
public:
student() {
cout << "调用构造函数"<< endl;
}
}; void main() {
//调用默认构造函数的几种方式
student stu1;
student stu2= student();
student *stu3 = new student;
}
注意
student stu1();//这是一个返回student对象的函数,而不是构造函数
c++11 列表初始化
student stu1 = { , };
2.析构函数
#include<iostream>
using namespace std;
class student {
public:
student() {
cout << "调用构造函数"<< endl;
}
~student() {
cout << "调用析构函数" << endl;
}
}; void main() {
{
student stu1;//这是一个返回student对象的函数,而不是构造函数
}
}
3.const成员函数
const成员函数内不运行修改成员属性,被添加mutable的成员函数可以被const函数修改
void sum(int &a,int b) const {//const放在方法的后面,使得该程序下成员函数不能被修改
a = ;
}
const指针修饰的是被隐藏的this指针所指向的内存空间,修饰的是this指针
三、this指针
this指针指向被调用的成员函数所属的对象。
this指针隐含每一个非静态成员函数内的指针。
用途:
this 同名参数
类的非静态成员函数中返回对象本身,可用return *this
四、对象数组
五、类作用域
六、抽象数据类型
文件头类声明
最新文章
- WinForm 对Web Api 增 册 改 查 的基本操作
- 在VS2012下静态链接MFC的问题
- 数据库:django ORM如何处理N+1查询
- 使用MVC过滤器保存操作日志
- HttpApplication 类,HttpApplicationState 类
- esriControlsMousePointer 控制鼠标指针
- Python socket模拟HTTP请求
- 命名空间“System.Web.Mvc”中不存在类型或命名空间名称“Ajax”(是否缺少程序集引用?)
- Repeater为空时显示“暂无数据”,很方便实用方法
- 通过 iTextSharp 实现PDF 审核盖章
- Abp中使用可视化的日志面板
- Photoshop调出清晰的阴雨天气山水风景照
- 使用ServletContext对象读取资源文件
- 简单对比git pull和git pull --rebase的使用
- 洛谷P3199 [HNOI2009]最小圈(01分数规划)
- Python splinter 环境搭建
- 启动HDFS之后一直处于安全模式org.apache.hadoop.hdfs.server.namenode.SafeModeException: Log not rolled. Name node is in safe mode.
- MySQL索引设计不可忽视的知识点
- Android MediaScanner
- selenium测试(Java)--学习总结