构造函数与析构函数

构造函数

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

析构函数

  • 每次删除所创建的对象时执行
  • 析构函数与构造函数类似,前面多个~
  • 不带任何参数
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 分钟前
【C++】C++ STL探索:Priority Queue与仿函数的深入解析
开发语言·c++·后端
ephemerals__12 分钟前
【c++】动态内存管理
开发语言·c++
CVer儿22 分钟前
条件编译代码记录
开发语言·c++
程序猿练习生1 小时前
C++速通LeetCode简单第18题-杨辉三角(全网唯一递归法)
c++·算法·leetcode
汉字萌萌哒1 小时前
【2022 CCF 非专业级别软件能力认证第一轮(CSP-J1)入门级 C++语言试题及解析】
数据结构·c++·算法
th新港1 小时前
CCF201909_1
数据结构·c++·算法·ccf
意如流水任东西1 小时前
[C++]类和对象(上)
开发语言·c++
孤寂大仙v1 小时前
【C++】STL----stack和queue常见用法
开发语言·c++
一丝晨光1 小时前
逻辑运算符
java·c++·python·kotlin·c#·c·逻辑运算符
Code哈哈笑3 小时前
【C++ 学习】多态的基础和原理(10)
java·c++·学习