构造函数与析构函数

构造函数

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

析构函数

  • 每次删除所创建的对象时执行
  • 析构函数与构造函数类似,前面多个~
  • 不带任何参数
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;
}
相关推荐
不想写代码的星星19 小时前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++
樱木Plus3 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit5 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_6 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星6 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛8 天前
delete又未完全delete
c++
端平入洛9 天前
auto有时不auto
c++
哇哈哈20219 天前
信号量和信号
linux·c++
多恩Stone9 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马9 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost