課程
/后端開發(fā)
/C++
/C++遠(yuǎn)征之封裝篇(上)
定義好了拷貝構(gòu)造函數(shù),也“刷出了存在感”但是就是按理想的結(jié)果輸出。比如t1=t2,t2可以輸出jim 5 150,但是t1輸出一堆看不懂的碼是什么情況?求大神給解答一下
2016-01-02
源自:C++遠(yuǎn)征之封裝篇(上) 6-8
正在回答
因?yàn)槟阕约簩?shí)現(xiàn)了拷貝構(gòu)造函數(shù),但是沒有在拷貝構(gòu)造函數(shù)里對(duì)成員變量進(jìn)行賦值,只是簡單的輸出了拷貝兩個(gè)字
培根熏肉 提問者
teacher.h頭文件如下:
#include?<stdlib.h> #include?<string> #include?<iostream> using?namespace?std; class?Teacher { public: void?setName(string?name); string?getName(); void?setAge(int?age); int?getAge(); int?getMax(); ????Teacher(string?name,?int?age=20); Teacher(); Teacher(const?Teacher&); private: string?m_strName; int?m_iAge; const?int?m_iMax; };
teacher.cpp 文件如下:
#include?"teacher.h" string?Teacher::getName() { return?m_strName; } int?Teacher::getAge() { return?m_iAge; } int?Teacher::getMax() { return?m_iMax; } Teacher::Teacher():m_iMax(100) { m_strName="jack"; m_iAge=23; cout<<"Teacher()"<<endl; } Teacher::Teacher(string?name,?int?age):m_iMax(100) { m_strName=name; m_iAge=age; cout<<"Teacher(string?name='jack',?int?age=23)"<<endl; } Teacher::Teacher(const?Teacher&):m_iMax(100) { cout<<"拷貝"<<endl; }
demo文件如下:
#include?<stdlib.h> #include?<iostream> #include?"teacher.h" using?namespace?std; int?main(void) { Teacher?t1; Teacher?t2("jack"); Teacher?t3(t1); Teacher?t4=t2; cout<<t1.getName()<<"?"<<t1.getAge()<<"?"<<t1.getMax()<<endl; cout<<t2.getName()<<"?"<<t2.getAge()<<"?"<<t2.getMax()<<endl; cout<<t3.getName()<<"?"<<t3.getAge()<<"?"<<t3.getMax()<<endl; cout<<t4.getName()<<"?"<<t4.getAge()<<"?"<<t4.getMax()<<endl; system("pause"); return?0; }
結(jié)果如下:
最好上傳一下源代碼和出問題的亂碼
舉報(bào)
封裝--面向?qū)ο蟮幕?,本教程力求幫助小伙伴們即學(xué)即會(huì)
Copyright ? 2025 imooc.com All Rights Reserved | 京ICP備12003892號(hào)-11 京公網(wǎng)安備11010802030151號(hào)
購課補(bǔ)貼聯(lián)系客服咨詢優(yōu)惠詳情
慕課網(wǎng)APP您的移動(dòng)學(xué)習(xí)伙伴
掃描二維碼關(guān)注慕課網(wǎng)微信公眾號(hào)
2016-01-05
因?yàn)槟阕约簩?shí)現(xiàn)了拷貝構(gòu)造函數(shù),但是沒有在拷貝構(gòu)造函數(shù)里對(duì)成員變量進(jìn)行賦值,只是簡單的輸出了拷貝兩個(gè)字
2016-01-03
teacher.h頭文件如下:
teacher.cpp 文件如下:
demo文件如下:
結(jié)果如下:
2016-01-02
最好上傳一下源代碼和出問題的亂碼