[英]Overriding C++ pure virtual functions
我有以下課程:
模式 class h 文件:
#pragma once
class Mode
{
public:
virtual int recv() = 0;
};
模式 class cpp 文件: -> 空
LocalMode class h-文件:
#pragma once
#include "Mode.h"
class LocalMode: public Mode
{
private:
public:
LocalMode();
int recv();
};
LocalMode class cpp 文件:
#include "LocalMode.h"
int LocalMode::recv(){
return 0;
}
以下是我的問題:
關鍵字“覆蓋”是否總是必要的? 如果沒有,最佳實踐是什么?
主要問題:我知道上面的代碼對我有用。 But I have the problem, that I basically have to "copy" the function signature of the pure virtual function out of the base class into my derived class. 如果我不知道基礎 class 有哪些純虛函數,會發生什么?
我上面的實現意味着我必須知道基礎 class 中可用的所有純虛函數。 我嘗試通過 Mode:: scope 和 LocalMode:: scope 訪問純虛擬 function 但在 Visual Studio 中我只是收到一些錯誤消息(我認為這些錯誤消息與此無關)
一些插件/智能感知? 我記得在 java 中,IntelliSense 通常幫助我並從抽象 class 中添加了所需的功能。 雖然我知道 java 在這個意義上(從抽象類繼承)與 c++ 有點不同,但我還想知道是否有任何工具可以幫助我自動包含這些工具?
瀏覽互聯網我找不到任何例子。 他們都假設,基礎 class 的所有純虛函數都是已知的......我只是在想象,如果我有一個帶有很多純虛函數的抽象 class 並且我忘記復制其中一個,在實例化 I 時會報錯...
先感謝您。
關鍵字“覆蓋”是否總是必要的? 如果沒有,最佳實踐是什么?
它從來不是“必要的”。 無論是否使用此關鍵字,覆蓋都有效。 它只是在這里幫助您防止諸如拼寫錯誤等問題。
struct A
{
virtual int foo();
};
struct B: public A
{
int fooo(); //whoops, not overriding, no compiler error
};
struct C: public A
{
int fooo() override; //compiler error, compiler noticed my typo
};
因此,當您想要覆蓋虛擬 function 時,最佳做法是始終使用override
關鍵字。
主要問題:我知道上面的代碼對我有用。 But I have the problem, that I basically have to "copy" the function signature of the pure virtual function out of the base class into my derived class. 如果我不知道基礎 class 有哪些純虛函數,會發生什么?
你不能不知道。 要從 class 派生,編譯器需要該 class 的完整定義,這通常意味着您有#include
d 它(並且您可以訪問該定義)。
我上面的實現意味着我必須知道基礎 class 中可用的所有純虛函數。 我嘗試通過 Mode:: scope 和 LocalMode:: scope 訪問純虛擬 function 但在 Visual Studio 中我只是收到一些錯誤消息(我認為這些錯誤消息與此無關)
您在尋找反射機制嗎? 它在 C++ 中不存在,因此您無法獲取給定 class 的 function 列表。 如果你想從另一個 function 調用純虛擬 function,那是行不通的,因為它們是純虛擬的。
一些插件/智能感知?
這對於 StackOverflow 來說顯然是題外話,但是 C++ 的 IDE 有很多,您應該可以輕松找到它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.