您的位置:首页 > 编程语言 > C语言/C++

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

2017-01-30 16:48 155 查看
噫,大概有些了解构造函数了,这大概是一下午反复折腾收到的最好回报了。

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++