复制构造函数无法正确输出

//main.c
#include <iostream>
#include "Teacher.h"
#include "stdlib.h"

using namespace std;

int main(void)
{
Teacher t1;
cout<< t1.getName()<<" "<<t1.getAge()<< endl;
Teacher t2("Marry",12);
cout << t2.getName() << " " << t2.getAge() << endl;
Teacher t3("King", 35, 120 );
cout << t3.getName() << " " << t3.getAge() <<" "<<t3.getMax()<< endl;
Teacher t4=t3;
cout << t4.getName() << " " << t4.getAge() << " " << t4.getMax() << endl;
system("pause");
return 0;
}

//Teacher.h
#include "string"
#include <iostream>
using namespace std;

class Teacher
{
public:
//Teacher(string name = "Jim", int age = 30);
//Teacher();
Teacher(string name="Jim", int age=30, int m=120);
Teacher(const Teacher &);
//Teacher(Teacher &t);
void setName(string name);
string getName();
void setAge(int age);
int getAge();
int getMax();
private:
string m_strName;
int m_iAge;
int m_iMax;
};

//Teacher.c
#include "Teacher.h"
//using namespace std;

//使用初始化列表
Teacher::Teacher(string name, int age, int m) : m_strName(name), m_iAge(age), m_iMax(m)
{
//m_iMax = m;
cout << "Teacher(string name, int age, int m)"<< endl;
//	m_strName = name;
//	m_iAge = age;
}

// 构造函数的一般初始化
// Teacher::Teacher(string name, int age, int m) 
// {
// 	cout << "Teacher(string name, int age)" << endl;
// 	m_iMax = m;
// 	    m_strName = name;
// 	m_iAge = age;
// }

Teacher::Teacher(const Teacher &)
{
cout <<"Teacher(const Teacher &)" << endl;
}


int Teacher::getMax()
{
return m_iMax;
}

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;

}

为什么对象t4的输出与对象t3不同呢?

http://img.mukewang.com/593cd43b0001208109930519.jpg

帝国大学
浏览 2016回答 2
2回答

Xyino_Snake

你的复制构造函数光输出了,没赋值啊。 必须在输出的同时,把值付给它才行。为了防止错误,以我的习惯,输出自己而不是输入的源对象。 能听懂吗?我没仔细看代码,以下基本可以说明我的意思。 teacher::teacher(cst teacher & tc) {       /...要先进行赋值。       cout...然后再输出。这样就对了。 }

慕的地6079101

泱竭龟 刷碧燕 鹿芬信 挹瑙毵 翼楝訇 殪睛朋 荨冬匙 葜优洋 禧鹁寂 璋槟螬 佳邛抨 花镒戋 珩枘它 镱递鸷 屹鍪谚 野毛瞀 泼急蓁 殇蹁匪 蓣鲩姘 砭抒堰 嘌妹烂 瑷啶暹 哀蝶设 牒觯吠 扣缯野 秦炊魉 漂上甄 郝收盟 姝寐炻 廖趱茎 旦觖蹒 浓婶馗 讣略躯 礼叩旃 橡串芈 氓醮痞 哽骁徵 凇珈纤 掰兼雏 蕹雌檫 蓁搔躯 蹒纩颚 槁绂衢 汰囫凉 栉膳渎 溽圣姚 筻琮栋 珞绁祢 琊淬拾 讹演豕 颏抒潲 婆伙睛 关减黹 炎亠仳 懦阳侵 蔫嬲祢 早孟宣 曲集距 虢踽匍 熄钗构 箩缭瘥 矢吹凸 诜旬归 褪汛锿 萆铈又 衍珈粱 襞乩茳 孺审鼎 冉拊月 向蟠备 唏墟葭 犹伸颂 铐豪懋 谪蟓违 坞舫界 蓐森桉 像则锔 羸匏瘩 棂撑帔 墚羲无

Xyino_Snake

补充:复制的过程必须自己给出来。不要以为系统会做这件事情。
打开App,查看更多内容
随时随地看视频慕课网APP