c2はc1の子であるため、関数getHi()を継承します。
まず、c2
「から派生する」、「の派生クラスである」、または「から継承する(あなたの場合は)」と言う必要がありますc1
。また、「継承」は正しい動詞です。
しかし、これを行うとどうなりますか?
この場合、からプライベートに継承するため、キャストを実行できませんc1
。の定義をc2
次のように変更すると、まったく同じように機能する2つの呼び出しが表示されますgetHi()
(この場合)。
class c2 : public c1 { };
// ^^^^^^
// This means that public members of c1 will become
// public members of c2 as well. If you specify nothing,
// public members of c1 will become private members of
// c2
クラス定義の後にセミコロンがないことにも注意してください。最も重要なのは、およびpublic
の定義にアクセス修飾子がないことです。これらがないと、コンストラクターがになり、これらのクラスをインスタンス化できなくなります。c1
c2
private
class c1
{
public: // <== Don't forget this!
c1() {} // Btw, why this? It does nothing
double getHi() { return _hi; }
private:
double _hi = 2;
}; // <== Don't forget this!
class c2 : public c1
// ^^^^^^ Don'f forget this!
{
public: // <== Don't forget this!
c2() {} // Btw, why this? It does nothing
}; // <== Don't forget this!
int main()
{
c2* b = new c2();
b->getHi(); // Compiles, calls c1::getHi();
((c1*)b)->getHi(); // Compiles, calls c1::getHi();
}