c++基础语法 构造函数 析构函数 类的组合
2024-08-25 06:41:21
1 构造函数
1.不能指定任何返回值,甚至连void都不能有。
2.与Java不同,c++不同new对象,对于无参的构造函数声明对象时括号应该省略。
2 析构函数
1. 前加~,不能有参数,不能有返回值。
2.每个类内只能声明一个析构函数并且公有。
3 类的组合
#include <iostream.h>
class A
{
public:
A(int x)
{
cout<<"class A construing\t\t"<<x<<endl;
}
~A()
{
cout<<"class A destroy"<<endl;
}
}; class B
{
public:
B()
{
cout<<"class B construing\t\t"<<endl;
}
//可以利用这种方式初始化私有变量
B(int x):b(x)
{
//b=x;
cout<<"class B construing\t\t"<<b<<endl;
}
~B()
{
cout<<"class B destroying"<<endl;
}
private:
int b;
}; class C
{
public:
C(int x,int y):a1(y)
{
cout<<"Class A with y ,C with xy construing, but B with nothing "<<x<<y<<endl;
}
C(int x,int a,int b);
~C()
{
cout<<"class C destroying"<<endl;
}
private:
A a1;
B b1;
}; C::C(int x,int a,int b):b1(b),a1(a)
{
cout<<"class A B C construing"<<x<<a<<b<<endl;
} int main()
{
C c1(,);
C c2(,,);
return ;
}
创建组合类时,将按内嵌对象在类中的声明先后顺序,而不是按成员初始化列表中的顺序,调用其相应的构造函数,最后调用该组合类的构造函数。
析构函数的调用正好相反。
在定义构造函数时,才可以带有成员的初始化列表,如果仅是声明构造函数,不可以带成员初始化列表。
必须指出成员初始化列表也可用于初始化类中的普通数据成员。
最新文章
- iOS 项目改名~~~~~
- Android文本读写
- Auto Clear Unity Console Log
- 20145215《Java程序设计》第1周学习总结
- 十 SSH
- SQL 查看数据库表的容量大小
- 了解Unix进程(1)
- Google map v3 using simple tool file google.map.util.js v 1.0
- 7.nginx伪静态规则
- IdentityServer4-介绍大纲(译文)
- PBRT笔记(10)——体积散射
- 【转】让Xcode支持iOS12.0 设备真机测试(不断更新真机支持包)Xcode 真机测试 iOS
- 2016521-Java-第八周学习总结
- MFC CEdit控件 自动换行
- ecstore-自定义app里增加对应的wap的模板
- bzoj4940: [Ynoi2016]这是我自己的发明
- Inception开源公告
- MySQL的启动与停止
- 图像数据到网格数据-1——MarchingCubes算法
- PHP搭建(windows64+apache2.4.7+mysql-5.6+php5.5+phpMyAdmin)和Discuz安装
热门文章
- sdut2536字母哥站队(dp)
- Linux kernel ‘xfs_attrlist_by_handle()’函数缓冲区溢出漏洞
- mybatis 应用参考
- Xcode 升级后, 插件无法使用的问题( PluginLoading: Required plug-in compatibility UUID.... )
- PHP静态化之真静态化
- REST Web 服务介绍
- LightOJ 1370 Bi-shoe and Phi-shoe 欧拉函数+线段树
- [转]NHibernate之旅(13):初探立即加载机制
- CentOS+Nginx一步一步开始配置负载均衡
- Unity 时间缩放状态下的特效播放