「已注销」 2023-03-18 20:04 采纳率: 100%
浏览 22
已结题

C++基类带参数构造函数问题


class test{
protected:
    int a;
public:
    test(int a = 0);
    ~test();
    void show();
};

class B :public test {
private:
    int b;
public:
    B(int b = 0);
    void show();
};
#include <iostream>
#include "test.h"
using namespace std;

test::test(int a) {
    cout << "a = " << a << endl;
    cout << "this a = " << this->a << endl;
    this->a = a;
    cout << "基类实例化:a : " << this->a << endl;
}

test::~test() {
    cout << "退出基类实例化" << endl;
}

void test::show() {
    cout << "a : " << a << endl;
}

B::B(int b) : test(a)
{
    cout << "派生类实例化" << endl;
    cout << "b = " << b << endl;
    cout << "this b = " << this->b << endl;
    this->b = a;
}

void B::show() {
    cout << "b : " << b << endl;
}

#include <iostream>
#include "test.h"
using namespace std;

int main() {
    B t1;
    t1.show();
    return 0;
}

img


请问为什么第一行的输出a不是0?
怎么改才能让第一行的输出a是0?

  • 写回答

3条回答 默认 最新

  • orbitgw C++领域新星创作者 2023-03-18 20:07
    关注

    在基类声明时赋值,即:

    class test{
    protected:
        int a = 0;
    public:
        test(int a);
        ~test();
        void show();
    };
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 3月26日
  • 已采纳回答 3月18日
  • 创建了问题 3月18日