构造函数与析构函数

构造函数

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

析构函数

  • 每次删除所创建的对象时执行
  • 析构函数与构造函数类似,前面多个~
  • 不带任何参数
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;
}
相关推荐
浅念-14 小时前
Linux 开发环境与工具链
linux·运维·服务器·数据结构·c++·经验分享
旺仔.29115 小时前
容器适配器:stack栈 、queue队列、priority queue优先级队列、bitset位图 详解
c++
刘景贤16 小时前
C/C++开发环境
开发语言·c++
OasisPioneer18 小时前
现代 C++ 全栈教程 - Modern-CPP-Full-Stack-Tutorial
开发语言·c++·开源·github
liulilittle18 小时前
XDP to TC : TUN eBPF NAT
c++
花开莫与流年错_18 小时前
ZeroMQ基本示例使用
c++·消息队列·mq·示例·zeromq
qq_4160187219 小时前
C++中的模板方法模式
开发语言·c++·算法
jyyyx的算法博客20 小时前
KMP 算法
c++·kmp
Emberone20 小时前
从C到C++:一脚踹开面向对象的大门
开发语言·c++
DDzqss20 小时前
3.25打卡day45
c++·算法