【问题标题】:polymorphism and protected inheritance issue多态性和受保护的继承问题
【发布时间】:2016-03-05 12:10:31
【问题描述】:

我有这个代码,并且在行中 tp = new asp_table,它不会让我编译说我没有访问权限。 我不明白为什么?我试图创建一个从基类到派生类的指针,但它不允许我这样做。我想知道为什么。

class table {    
    int size;     
    int priority;   

    public:       
    table(int s=0,int p=0):size(s),priority(p){ }
    virtual void print(){}
};

class stud_table:public table {   
    char * name;  
    int gr;

    public: 
    void print() {cout<<"students table"<<endl;}  
    ~stud_table() {delete []name;} 
};

class asp_table:protected table { 
    char* thesis;
}; 

int main() {  
    stud_table st;   
    table * tp = &st; 
    tp = new asp_table;
    stud_table * stp = &st;   
    cout<<"Program"<<endl;    
    return 0;
} 

【问题讨论】:

  • 访问什么?请在您的问题中添加完整的错误消息。
  • 错误:不允许转换为无法访问的基类“表”。

标签: c++ oop pointers c++11


【解决方案1】:

错误信息说明了一切:

无法将“asp_table”转换为其受保护的基类“表”

protected 继承意味着只有asp_table 及其派生类知道继承。因此tp = new asp_table 在类或其派生类之外是不可能的。

【讨论】:

  • 非常感谢您的评论 :( 但我还是不明白......所以当派生类继承为受保护时,我基本上不能使用多态性?
  • 是的,不在类或其派生类之外。这就是受保护的继承的含义。看来您想使用公共继承。
猜你喜欢
  • 2015-01-19
  • 1970-01-01
  • 1970-01-01
  • 2015-03-02
  • 1970-01-01
  • 2012-09-26
  • 2023-03-23
  • 2014-01-30
  • 1970-01-01
相关资源
最近更新 更多