看板 C_and_CPP 關於我們 聯絡資訊
內部變數的資料儲存變化大概如下 b1(1,2) Base Base::computer Base value1 = 1 ===> value1 = 4 value2 = 2 value2 = 6 -------------------------------------------------------------- d1(2,3,4) Base Base value1 = 2 value1 = 7 value2 = 3 Base::computer value2 = 15 ===> Derived Derived value2 = 5 value2 = 5 value3 = 4 value3 = 4 -------------------------------------------------------------- d2(3,4,5) Base Base value1 = 3 value1 = 3 value2 = 4 None value2 = 4 ===> Derived Derived value2 = 7 value2 = 7 value3 = 5 value3 = 5 -------------------------------------------------------------- d3(4,5,6) Base Base value1 = 4 value1 = 3 value2 = 5 value2 = 5 Virtual Derived::calculate Derived ===> Derived value2 = 9 value2 = 6 value3 = 6 value3 = 4 --------------------------------------------------------------- d4(5,6,7) Base Base value1 = 5 value1 = 7 value2 = 6 value2 = 12 Base::compute Derived ===> Derived value2 = 11 value2 = 11 value3 = 7 value3 = 7 Base value1 = 4 value2 = 12 Virtual Derived::calculate ===> Derived value2 = 8 value3 = 5 ---------------------------------------------------------------- new Derived(6, 7, 8) Base Base value1 = 6 value1 = 5 value2 = 7 value2 = 7 Base::compute1 Derived Virtual Derived::calculate Derived value2 = 13 ===> value2 = 10 value3 = 8 value3 = 6 ※ 引述《hyujr (鬱)》之銘言: : 因為本身只學過C語言也沒學得很深 : 突然發現考題裡面有C++有點嚇到 : 不過就硬頭皮把程式碼打下來 : 邊想邊對照Output : 後來做了幾份大概有些概念 : 雖然也不確定到底思考的流程是不是對的= = : 但有個地方實在想不通 : 不知道有沒有人可以幫我說明一下.. : # include <string> : # include <iostream> : class Base : { : public: : Base(int b1 = 0, int b2 = 0) {value1 = b1; value2 = b2;} : void compute(int x) {value1 += x; value2 *= x;} : void compute1(int x) {calculate(x);} : virtual void calculate(int x) {value1 = x; value2 = x * x;} : void print() {cout << value1 + value2 << " ";} : int value1, value2; : }; : class Derived: public Base : { : public: : Derived(int x1, int x2, int x3):Base(x1, x2) : {value2 = x1 + x2; value3 = x3;} : virtual void calculate(int x) {value1 = x; value2 = 2 * x; value3 = x + 1;} : void print() {cout << value2 + value3 << " ";} : int value2, value3; : }; : void main() : { : Base b1(1, 2); b1.print(); : b1.compute(3); b1.print(); : Derived d1(2, 3, 4); d1.print(); : d1.compute(5); d1.Base::print(); : Derived d2(3, 4, 5); Base b2; b2 = d2; b2.print(); : Derived d3(4, 5, 6); d3.calculate(3); d3.print(); : d3.Base::print(); //這行 : Derived d4(5, 6, 7); Base *b4; b4 = &d4; b4->compute(2); b4->print(); : b4->calculate(4); d4.print(); : Base *b5 = new Derived(6, 7, 8); b5->compute1(5); b5->print(); //這行 : system("pause"); : } : 有標記那兩行的所輸出結果想不通 : 有沒有人可以幫我說明一下~ : 謝謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 124.8.148.16
hyujr:是因為還沒有真正搞懂C++的語法.. 03/06 00:33
hyujr:真是太感謝這麼詳細圖解! 03/06 00:34