9

C++ クラスでは、派生クラスに親クラスから変数を継承させることができます。var2で継承されないように派生クラスを定義するにはどうすればよいderivclassですか?

class mainclass{
public:
    int var1;
    char var2;
    void test(){
        cout<<var1<<var2<<endl;
    }
}
class derivclass : mainclass{
public:
    void test(){
        cout<<var1<<var2<<endl;
        //want a compiler error here that var2 is not defined
    }
}
4

5 に答える 5

0

他のすべての回答に応じて (確率的にピギーバックする可能性もあります)、メイン クラスと派生クラスを切り替えることができます。新しいメイン クラスには、元の派生クラスで必要なすべてのメンバー値が含まれ、不要なものが配置されます。新しい派生クラス (別名、元のメイン クラス)

観察:

class newMainClass{
public:
    int var1;
    virtual void test(){ //added virtual here so there aren't two definitions for test()
        cout<<var1<<var2<<endl;
        //want a compiler error here that var2 is not defined
    }
}

class newDerivedClass : public newMainClass{
public:
    char var2;
    void test(){
        cout<<var1<<var2<<endl;
    }
}
于 2016-08-01T23:07:40.837 に答える