C++拷贝构造函数

如果没有编写,编译器会为每个类自动生成几个构造函数,无参数的默认构造函数,带参数的拷贝构造函数,赋值构造函数(operator=)。


#include "iostream.h"
#include "string.h"

class Pen
{
private:
	int m_size;
public:
	Pen(int size=0);
	Pen(Pen &pen);
	int GetSize();
	void Write();
};

Pen::Pen(int size)
{
	m_size = size;
}

Pen::Pen(Pen &pen)
{
	m_size = pen.GetSize();//pen.m_size;
	cout<<"复制size的值为:"<<m_size<<endl;
}

int Pen::GetSize()
{
	return m_size;
}

void Pen::Write()
{
	cout<<"size的值为"<<GetSize()<<endl;
}

int main(int argc, char *argv[])
{
	Pen pen1(10);
	pen1.Write();
	Pen pen2(pen1);//调用拷贝构造函数
	pen2.Write();
	Pen pen3 = pen2;//调用拷贝构造函数
	pen3.Write();

	Pen pen4;
	pen4 = pen1;
	pen4.Write();//调用赋值构造函数 oprator=

	return 0;
}


你可能感兴趣的:(C++,编译器)