构造函数与析构函数

构造函数

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

析构函数

  • 每次删除所创建的对象时执行
  • 析构函数与构造函数类似,前面多个~
  • 不带任何参数
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;
}
相关推荐
apocelipes2 分钟前
记一次ADL导致的C++代码编译错误
c++·开发工具和环境
Code Warrior1 小时前
【每日算法】专题五_位运算
开发语言·c++
OneQ6666 小时前
C++讲解---创建日期类
开发语言·c++·算法
Coding小公仔8 小时前
C++ bitset 模板类
开发语言·c++
菜鸟看点8 小时前
自定义Cereal XML输出容器节点
c++·qt
悲伤小伞9 小时前
linux_git的使用
linux·c语言·c++·git
ysa05103010 小时前
数论基础知识和模板
数据结构·c++·笔记·算法
小小小小王王王13 小时前
求猪肉价格最大值
数据结构·c++·算法
岁忧13 小时前
(LeetCode 面试经典 150 题 ) 58. 最后一个单词的长度 (字符串)
java·c++·算法·leetcode·面试·go
码农编程录14 小时前
【c/c++3】类和对象,vector容器,类继承和多态,systemd,std&boost
c++