iT邦幫忙

0

C++ oop問題

  • 分享至 

  • twitterImage

準備期中考的一些問題,來版上求助QAQ
希望大家能教我,非常感謝
.
第一題
哪些程式碼是危險的
答案應該是第四行&倒數第二行
為甚麼阿?

Class Test
{
public:
	Test()  {	ptr = new int[20]; }
	~Test() {	delete [] ptr; }
private:
	int *ptr;
};

void main()  {
	Test A;
	Test B;
	B=A;
}

.
第二題
英文題目:Please implement a link list container (class) to run the following main function and output the results correctly.
中文意思應該是如何寫出正確的link list class吧
題目程式碼如下

void main()
{
    	Link_List<int> linkList1;
    	linkList1.insert_node(5);	linkList1.insert_node(12);
    	linkList1.insert_node(6);	linkList1.insert_node(8);

    	cout << "linkList1: " << linkList1 << endl;
    
Link_List linkList2 = linkList1;
    	cout << "linkList2[1]: " << linkList2[1] << endl;
    	cout << "linkList2[3]: " << linkList2[3] << endl;
}

且結果如下
Output
LinkList1: 5 12 6 8
LinkList2[1]: 12
LinkList2[3]: 8
(我不知道怎麼讓[1]=12以及[3]=8...)
.
第三題
英文題目:Declare the Array class and overload the operator << for ostream class so that the following main function can run smoothly. Note that you need to prevent people from writing the code such as "(x=y)=z" when using your class.
中文題目的意思大概是說 要完成這個array class,使用operator<<,且須避免x=y=z
題目程式碼如下

void main() 
{
	Array<int> nList, mList;
	nList.resize(5);
	nList[0] = nList[1] = nList[2] = nList[3] = nList[4] = 5;
	mList = nList;
	cout << mList << endl;
}

答案程式碼如下

class Array
{
	friend ostream & operator<<(ostream &output , const Array &);
public:
	Array();
	void resize(int);
	int & operator[](int);
	const Array & operator=(Array &);
private:
	int *arr;
};

ostream & operator<<(ostream &output , const Array &);

(我不知道為甚麼答案的程式碼可以做出避免x=y=z,看不太懂程式碼...)

非常感謝版上的大家願意教我QAQ
真的很感謝...ˊˋ

sunnyyeh iT邦新手 5 級 ‧ 2019-07-28 11:41:58 檢舉
能不能幫我解釋第一題跟第三題 拜託?
sunnyyeh iT邦新手 5 級 ‧ 2019-07-28 11:42:12 檢舉
感謝感謝
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
小碼農米爾
iT邦高手 1 級 ‧ 2019-07-29 09:28:32
最佳解答

第一題
小弟我也不是很確定,我猜測給你參考看看
B=A 會呼叫 複製建構式,這時 B 的 ptr 會被覆蓋變成指向 A 的 ptr,B 的解構式呼叫時就不會釋放自己在建構式 new 出來的空間,因為原指標已經被改變。

第二題
這題應該是實作 Link_List & operator[](int index),在函數裡面跑迴圈從頭開始找到第 index 個項目。

第三題
const Array & operator=(Array &);
operator= 回傳型態是 const 表示回傳的結果不能被更改。
因此 z 不能再賦值給 (x=y)
(x=y)=z

DanSnow iT邦好手 1 級 ‧ 2019-07-29 22:36:25 檢舉

補充一下第一題,最有問題的是在 B = A 後兩個的 ptr 是同一個,而在解構式中又會對 ptrdelete,從而導致 dobule free

0
小魚
iT邦大師 1 級 ‧ 2019-07-28 13:43:42

第一題
第四行我看不出什麼問題,
不過倒數第二行 A = B,
這個會有問題,
因為Test不是C++固有的類別,
沒有=的定義,
這時候你需要 運算子重載

第三題
原來是要自己定義一個Array的Class喔,
不過看起來最後還是沒有定義 = 跟 << 啊,
其他函式似乎也沒有定義,
我覺得這只能算是未完成品吧...

我要發表回答

立即登入回答