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

C++默认构造函数、继承与覆写问题:编译报错及基类打印异常

#include <iostream>

using namespace std;

class Base {
    int x;
public:
    Base() : x() {}
    Base(int x) : x(x) {}
    virtual void print() const {
        cout << x << endl;
    }
};

class Derived : public Base {
    int x, y;
public:
    Derived(int x, int y) : x(x), y(y) {}
    void print() const override {
        cout << x << ", " << x << endl;
    }
};

int main() {
// All data members of Base and Derived classes must be declared 
// as private access types
    Base* p1 = new Derived(10, 20);     // (x, y)
    Base* p2 = new Base(5);         // (x) 
    p1->print();            // prints 10, 20
    p1->Base::print();      // prints 10
}

问题1解答

你遇到的编译提示,核心原因是:创建Derived对象时,编译器会先初始化它的Base基类部分。你的Derived构造函数初始化列表里没有显式指定要调用Base的哪个构造函数,所以编译器会自动尝试调用Base的默认构造函数。

虽然你确实定义了Base的默认构造函数,但这个提示可能源于你对构造函数初始化范围的误解——你在Derived构造函数里初始化的x是Derived自己的成员变量,和Base的x毫无关联。如果想消除这个提示,或者让Base的x被你指定的值初始化,可以在Derived的构造函数初始化列表里显式调用Base的带参构造函数,示例如下:

Derived(int x, int y) : Base(x), x(x), y(y) {}

问题2解答

p1->Base::print()无法打印10,是因为Base的x成员并没有被初始化为10——当前Derived构造函数只初始化了自己的x和y,Base的x是通过默认构造函数被初始化为0的,所以调用Base::print()会输出0。

要实现预期效果,需要修改Derived的构造函数,显式调用Base的带参构造函数,把要传给Base的x值传进去,修改后的构造函数如下:

Derived(int x, int y) : Base(x), x(x), y(y) {}

另外注意,你的Derived::print()函数里写的是cout << x << ", " << x << endl;,这里第二个x应该改成y,否则会输出10, 10而不是预期的10, 20,修正后:

void print() const override {
    cout << x << ", " << y << endl;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 00:55:17