为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C++
帝国大学 2017-06-11 13:26:02
//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不同呢?
查看完整描述

2 回答

?
Xyino_Snake

TA贡献31条经验 获得超22个赞

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

查看完整回答
1 反对 回复 2017-06-11
?
Xyino_Snake

TA贡献31条经验 获得超22个赞

补充:复制的过程必须自己给出来。不要以为系统会做这件事情。

查看完整回答
反对 回复 2017-06-11
  • 2 回答
  • 0 关注
  • 2009 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信