2016-04-29 16 views
-4

私は基底クラスAと2つのクラスB、Cを持っています。メソッドfuncの宣言はクラスAで与えられます。 ?派生クラスで未定義の基本クラスのメソッドを定義する

class A { 
public: 
    void func(); 
}; 

class B : public A { 
//some members 
}; 

class C : public A { 
//some members 
}; 

//define B's func here without changing the definition of the three classes 
//define C's func here without changing the definition of the three classes 
+2

これはC++で_very_基本的なトピックであるとC++の本で覆われています。私はあなたが[C++の良い本](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)を拾うことをお勧めします。 –

+0

"virtual"ディレクティブを使用しないとできません。 A :: func()のアドレスはB :: func()またはC :: func()によって上書きされなければならず、レイトバインドを行う場合にのみ実行できます。 – Vink

答えて

2

あなたは「仮想」または「純粋仮想」上書きする方法を確認する必要がありますし、クラスが仮想メソッドを持っている場合、また、デストラクタは仮想である必要があります。

class A { 
public: 
    virtual ~A{}; 
    virtual void func() = 0; 
}; 

class B : public A { 
    void func() {}; 
}; 

class C : public A { 
    void func() {}; 
}; 
+0

.... "3つのクラスの定義を変更することなく" – newuser

+1

@ newuser:変更せずにはできません。 – cwschmidt

2

いいえ、あなたは、クラスで宣言されていないクラスのメンバ関数を実装することはできません。

class A { 
public: 
    void func(); 
}; 

class B : public A { 
//some members 
}; 

class C : public A { 
//some members 
}; 

void B::func() {} 
void C::func() {} 
/tmp/164435074/main.cpp:17:9: error: out-of-line definition of 'func' does not match any declaration in 'B' 
void B::func() {} 
     ^~~~ 
/tmp/164435074/main.cpp:18:9: error: out-of-line definition of 'func' does not match any declaration in 'C' 
void C::func() {} 
     ^~~~ 
関連する問題