爱睡懒觉的猫猫 2022-04-15 10:53 采纳率: 85.7%
浏览 33
已结题

C++简单的类继承问题

下面是我的代码,它会在子类的构造函数那里报错,像这样要怎么改呀?


BASE::BASE(int p1,int p2){
    mem1=p1;
    mem2=p2;
}
void BASE::display()const{
    cout<<"mem1="<<mem1<<",mem2="<<mem2<<endl;
}
int BASE::inc1(){
    mem1++;
}
DERIVED::DERIVED(int x1, int x2, int x3, int x4, int x5){
    BASE.BASE(x1,x2);
    mem4.BASE(x3,x4);
    mem3=x5;
}
int DERIVED::inc1(){
    mem3++;
}
void DERIVED::display() const{
    BASE.display();
    mem4.display();
    cout<<"mem3="<<mem3<<endl;
}

题目要求

img

下面是题目所给代码,完成两个类函数


#include <iostream>
#include <cstdlib>
//#include "DERIVED.h"

using namespace std;

int main() {
    
    DERIVED obj(17, 18, 1, 2, -5);
    obj.inc1();
    obj.display();


    return 0;
}
#ifndef DERIVED_H
#define DERIVED_H
//#include "BASE.h"

class DERIVED : public BASE{
    public:    
        DERIVED(int x1, int x2, int x3, int x4, int x5);
         int inc1() ;
         void display( ) const ;

    private:           
        int mem3;
        BASE mem4;
};


#endif
#ifndef BASE_H
#define BASE_H
#include <iostream>
using namespace std;

class BASE {
    public: 
        BASE(int p1, int p2);
        int inc1();    
        void display() const; 
    
    private:
        int mem1, mem2;
};                                 

#endif
  • 写回答

1条回答 默认 最新

  • 无夜_ 2022-04-15 11:15
    关注

    1 在子类构造函数的初始化列表中直接调BASE()
    2 子类构造中调用BASE::BASE()试试

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 4月23日
  • 已采纳回答 4月15日
  • 创建了问题 4月15日

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图