【C++Primer】封装_拷贝构造函数

本文通过一个具体的C++示例介绍了构造函数与拷贝构造函数的基本概念及使用方式。通过对Teacher类的定义和实例化,展示了不同构造函数的作用及其在对象创建和复制过程中的调用情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

噫,大概有些了解构造函数了,这大概是一下午反复折腾收到的最好回报了。


#include <stdio.h>
#include <iostream>
#include <string>
#include "Teacher.h"
using namespace std;
class Teacher
{
public:
	Teacher(string name="Ludwing",int age=26);
	Teacher(const Teacher &tea);//声明拷贝构造函数;
	void setName(string name);
	string getName();
	void setAge(int age);
	int getAge();
private:
	string m_strName;
	int m_iAge;
};
Teacher::Teacher(string name,int age):m_strName(name),m_iAge(age)
{
	cout<<"Teacher(string name,int age)"<<endl;
}
Teacher::Teacher(const Teacher &tea)
{
	cout<<"Teacher(const Teacher &tea)"<<endl;
}
void Teacher::setName(string name)
{
	m_strName=name;
}
string Teacher::getName()
{
	return m_strName;
}
void Teacher::setAge(int age)
{
	m_iAge=age;
}
int Teacher::getAge()
{
	return m_iAge;
}
void test(Teacher t)
{

}
int main()
{
	Teacher t1;//调用t1时使用的是正常的构造函数;
	test(t1);//调用test时触发了拷贝过程,所以用到了拷贝构造函数;
	Teacher t2(t1);//调用t2,t3时使用的是拷贝构造函数;
	Teacher t3=t1;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值