課程
/后端開發(fā)
/C++
/C++遠(yuǎn)征之封裝篇(下)
coorArr不是對(duì)象嗎 為什么執(zhí)行不了
2017-12-10
源自:C++遠(yuǎn)征之封裝篇(下) 2-9
正在回答
數(shù)組當(dāng)中每一個(gè)元素,不管是什么類型都是對(duì)象。
你傳遞進(jìn)去一個(gè)1,2,這算什么?最多只能算是一個(gè)int類型的數(shù)據(jù)
并且也根本調(diào)用不了Cooordinate這個(gè)類的構(gòu)造方法
所以,你需要在數(shù)組元素當(dāng)中 = { Coordinate(1,2)}
這才是一個(gè)對(duì)象的元素
既然都是public成員,可以不改構(gòu)造函數(shù),直接這樣寫:
? ? Coordinate coorArr[2];
? ? coorArr[0].m_iX = 1;
? ? coorArr[0].m_iY = 2;
? ? coorArr[1].m_iX = 3;
? ? coorArr[1].m_iY = 4;
coordinate不是類名嗎
#include?<iostream> using?namespace?std; class?Coordinate { public: Coordinate(int?x,int?y) {?m_iX=x; ??m_iY=y; } //?打印坐標(biāo)的函數(shù) void?printInfo() { ???cout<<"("<<m_iX<<","<<m_iY<<")"<<endl; } private: int?m_iX; int?m_iY; }; int?main(void) { //定義對(duì)象數(shù)組 ???Coordinate?coorArr[2]?=?{Coordinate(1,2),Coordinate(3,4)}; //遍歷數(shù)組,打印對(duì)象信息 for(int?i?=?0;?i?<?2;?i++) { coorArr[i].printInfo(); } return?0; }
Coordinate coorArr[2] = {Coordinate(1,2),Coordinate(3,4)};
這句錯(cuò)了,數(shù)組里面需要再次用類名調(diào)用構(gòu)造函數(shù)
舉報(bào)
封裝--面向?qū)ο笕筇卣髦唬ㄟ^(guò)案例讓C++所學(xué)知識(shí)融會(huì)貫通
Copyright ? 2025 imooc.com All Rights Reserved | 京ICP備12003892號(hào)-11 京公網(wǎng)安備11010802030151號(hào)
購(gòu)課補(bǔ)貼聯(lián)系客服咨詢優(yōu)惠詳情
慕課網(wǎng)APP您的移動(dòng)學(xué)習(xí)伙伴
掃描二維碼關(guān)注慕課網(wǎng)微信公眾號(hào)
2018-01-23
數(shù)組當(dāng)中每一個(gè)元素,不管是什么類型都是對(duì)象。
你傳遞進(jìn)去一個(gè)1,2,這算什么?最多只能算是一個(gè)int類型的數(shù)據(jù)
并且也根本調(diào)用不了Cooordinate這個(gè)類的構(gòu)造方法
所以,你需要在數(shù)組元素當(dāng)中 = { Coordinate(1,2)}
這才是一個(gè)對(duì)象的元素
2018-03-22
既然都是public成員,可以不改構(gòu)造函數(shù),直接這樣寫:
? ? Coordinate coorArr[2];
? ? coorArr[0].m_iX = 1;
? ? coorArr[0].m_iY = 2;
? ? coorArr[1].m_iX = 3;
? ? coorArr[1].m_iY = 4;
2017-12-10
coordinate不是類名嗎
2017-12-10
Coordinate coorArr[2] = {Coordinate(1,2),Coordinate(3,4)};
這句錯(cuò)了,數(shù)組里面需要再次用類名調(diào)用構(gòu)造函數(shù)