构造函数与析构函数

构造函数

  • 每次创建类的新对象时执行
  • 构造函数的名称与类名相同,不带类型,可以有参数也可以没参数
  • 构造函数有时给成员函数付初值

析构函数

  • 每次删除所创建的对象时执行
  • 析构函数与构造函数类似,前面多个~
  • 不带任何参数
cpp 复制代码
#include "iostream"

using namespace std;

class Line
{
	public:
		void setLength(int len);
		int getLength();
		Line();
		~Line();
		
	private:
		int length;
 } ;
 
Line :: Line()
{
	cout << "创建了一个对象" << endl; 
}

Line :: ~Line()
{
	cout << "删除了一个对象" << endl; 
}

void Line :: setLength(int len)   //注意:前面需要类型
{
	length = len;
}

int Line :: getLength()
{
	return length;
}

int main(void)
{
	Line line;
	line.setLength(7);
	cout << "length is " << line.getLength() << endl;
}
相关推荐
郝学胜-神的一滴4 小时前
中级OpenGL教程 013:渲染器类架构设计与逐帧渲染流程详解
开发语言·c++·unity·游戏引擎·图形渲染·opengl·unreal
小小龙学IT5 小时前
C++ 并发编程深度解析:从内存模型到无锁数据结构
数据结构·c++
凯瑟琳.奥古斯特5 小时前
力扣1013三等分解法与C++实现
开发语言·c++·算法·leetcode·职场和发展
一拳一个呆瓜6 小时前
【STL】iostream 编程:缓冲区的作用
c++·stl
我不是懒洋洋6 小时前
从零实现一个分布式任务调度器:XXL-JOB的核心设计
c++
凯瑟琳.奥古斯特7 小时前
力扣1012数位DP解法详解
开发语言·c++·算法·leetcode·职场和发展
chh5637 小时前
C++--string
java·开发语言·网络·c++·学习
J_yyy8 小时前
基于Reactor的文件管理服务开发笔记
c++·笔记·reactor·多线程编程·muduo
李小小钦8 小时前
D. Storming Arasaka(Codeforces 2238)
c语言·开发语言·数据结构·c++·算法