Re: [問題] 繼承習題問題

作者: putumaxally (putumaxally)   2014-06-01 23:53:23
※ 引述《APE36 (PT鄉民)》之銘言:
: 開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
: 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
: 問題(Question):
: 餵入的資料(Input):
: 預期的正確結果(Expected Output):
: 錯誤結果(Wrong Output):
: 程式碼(Code):(請善用置底文網頁, 記得排版)
: 補充說明(Supplement):
: #include <iostream.h>
: class CA{
: public:
: CA(){a=30; b=40; c=50; }
: int a, b, c;
: };
: class CB: public CA{
: public:
: CB(){ x=10; y=20;}
: int x, y;
: int getM(){ return x*y; }
: int getN(){ return CA::a*CA::b*c/x; }
: };
: main()
: {
: CB b;
: b.CB::x = 5;
: b.a = 1;
: b.CA::a = 5;
: b.c = 2;
: cout<< "result= "<< b.getM()<< endl;
: cout<< "result= "<< b.getN()<< endl;
: }
: 請問這兩個答案輸出
: 會100,80
: 不懂他的trace code
: 希望有人肯解析一下,桑Q
我沒看過 iostream.h 還有沒有用 namespace 可以直接用 cout 跟 endl
還蠻奇怪的
#include <iostream>
using namespace std;
class CA
{
public:
CA(){a=30; b=40; c=50; }
int a, b, c;
};
class CB: public CA
{
public:
CB(){ x=10; y=20;}
int x, y;
int getM(){ return x*y; }
int getN(){ return CA::a*CA::b*c/x; }
};
main()
{
CB b;
// x = 10, y = 20, a = 30, b = 40, c = 50
b.CB::x = 5;
// x = 5, y = 20, a = 30, b = 40, c = 50
b.a = 1;
// x = 5, y = 20, a = 1, b = 40, c = 50
b.CA::a = 5;
// x = 5, y = 20, a = 5, b = 40, c = 50
b.c = 2;
// x = 5, y = 20, a = 5, b = 40, c = 2
cout<< "result= "<< b.getM()<< endl;
cout<< "result= "<< b.getN()<< endl;
}
b.CB::x 這是正式用法嗎?
作者: loveme00835 (髮箍)   2014-06-02 00:33:00
是的, 但是通常用在和父類別有同名資料成員的情況http://ideone.com/OQDz9i 在原文 code 顯得很多餘其實沒差, 因為的參數型別是int
作者: putumaxally (putumaxally)   2014-06-02 01:10:00
知道了,感謝

Links booklink

Contact Us: admin [ a t ] ucptt.com