You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++基类不可访问报错求助:多态与纯虚函数代码问题

问题分析与解决

编译错误核心原因

C++中类的默认继承方式是private继承:

  • 代码里class studentone:studenttemplate等价于class studentone:private studenttemplate
  • private继承会将基类的所有成员变为派生类的private属性,外部无法通过派生类对象访问基类,也就无法将派生类指针赋值给基类指针,因此编译器提示基类不可访问。

修复步骤

1. 修改继承方式为public

将派生类的继承改为public,确保基类的public接口在派生类中保持可访问性:

#include <iostream>

using namespace std;

class studenttemplate
{
    public:
    virtual void studentname()=0;
};

// 改为public继承studenttemplate
class studentone:public studenttemplate
{
    public:
    void studentname()
    {
        cout<<"my name is student one and im in college "<<endl;
    }
};

// 同理,studenttwo继承studentone也需用public
class studenttwo:public studentone
{
    public:
    void studentname()
    {
        cout<<"my name is student two and im in college "<<endl;
    }
};

2. 修复main函数的野指针问题

studenttemplate *n;是未初始化的野指针,直接*n = studentone();会触发未定义行为(程序崩溃),有两种修复方案:

方案一:使用栈对象(更安全,无需手动释放内存)

int main()
{
    studentone s1;
    studenttwo s2;
    
    studenttemplate* n = &s1;
    n->studentname();
    
    n = &s2;
    n->studentname();
    
    return 0;
}

方案二:使用动态分配(需手动管理内存)

int main()
{
    studenttemplate *n = new studentone();
    n->studentname();
    
    delete n; // 释放之前的内存,避免泄漏
    n = new studenttwo();
    
    n->studentname();
    
    delete n; // 最后释放内存
    return 0;
}

最终完整可运行代码

#include <iostream>

using namespace std;

class studenttemplate
{
    public:
    virtual void studentname()=0;
};

class studentone:public studenttemplate
{
    public:
    void studentname() override // 加override明确重写虚函数,编译器会做语法检查
    {
        cout<<"my name is student one and im in college "<<endl;
    }
};

class studenttwo:public studentone
{
    public:
    void studentname() override
    {
        cout<<"my name is student two and im in college "<<endl;
    }
};

int main()
{
    studentone s1;
    studenttwo s2;
    
    studenttemplate* n = &s1;
    n->studentname();
    
    n = &s2;
    n->studentname();
    
    return 0;
}

额外提示

  • 重写虚函数时建议加override关键字,避免因函数签名(参数、返回值)不一致导致的隐式函数隐藏问题。
  • 永远不要使用未初始化的指针,这是C++程序崩溃的常见诱因。

内容的提问来源于stack exchange,提问作者Unknown_User

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 00:17:42