2016-02-12 66 views
-4

我有從抽象類派生的類,我試圖將其傳遞作爲成員類派生的一個作爲自變量的成員函數的參數。我也有前向聲明問題。有什麼建議麼?通行證基類如在派生

class base; 
void print(*base); 


class base { 
public: 
const int number = 5; 
// ... virtual funcs etc. 
};  

class derived:public base { 
public: 
void test() { 
print(&base); // I guess here is the mistake 
}; 

void print(*base) { 
cout << base->number << endl; 
} 
+0

投票結束這個問題 - 它對任何人都沒有用處,代碼幾乎是隨機的。 – SergeyA

回答

1

只是不要print(this)(見online example)。你不能拿到一堂課的地址。

+0

'this'返回一個指向派生類的指針,而不是我想要的。 錯誤: 無效的用戶定義的從「衍生*」到「基地和」 – user4168715

+0

我想轉換'print'在您的實際代碼爲'無效打印(鹼基)'聲明。在這種情況下,使用'print(* this);'。 – TartanLlama

0

類是一類。類型沒有地址,只有變量。你似乎也缺乏對C++的基本理解。

void print(*base); 

完全是廢話。你必須回到書上。

0

指針到一個類的對象可以隱式轉換爲指針,它們的基類,所以你可以通過this,讓標準轉換髮生:

void test() { 
    print(this); 
}; 
0

I have a derived class from an abstract class, and I am trying to pass it as an argument of a member class of the derived one. I also have a forward declaration issue. Any suggestions?

你向前聲明是錯誤的。這是C++,不去,因此:

void print(base* pointerToBase); 

是正確的。除此之外,Alf的答案是對的。我寧願使用引用指針,因爲print通常不會修改狀態,請將其設置爲const。然後你的代碼變爲:

class base { 
public: 
const int number = 5; 
// ... virtual funcs etc. 
};  

void print(const base&); 

class derived:public base { 
public: 
void test() { 
print(*this); 
}; 

void print(const base& b) { 
cout << base.number << endl; 
}