基类和派生类中的构造函数

Constructor in base and derived class

本文关键字:构造函数 派生 基类      更新时间:2023-10-16

程序工作,但我不确定什么是错误的构造函数,因为每次程序运行它得到这个错误"警告:基类'Alat'是未初始化时使用这里访问'Alat::时间' [-Wuninitialized]"。我想这是错误的,我如何从基类调用构造函数,但我不确定是什么问题。真的需要帮助,请提前通知。

#include <iostream>
#include <string>
using namespace std;
class Alat{
protected:
    string ime;
    int serBr;
    int cena;
public:   
    void setIme(string i);
    string getIme();
    void setSerBr(int sb);
    int getSerBr();
    void setCena(int c);
    int getCena();
    Alat();
    Alat(string i, int sb, int c)
    :ime(i),
     serBr(sb),
     cena(c)
    {}
    void info();

    ~Alat();
};

#include "Alat.h"
class Rucni : public Alat{
protected:
    int minGodKor;
public:    
    Rucni():Alat(ime, serBr, cena)  //I think here is problem, is it wrong called?    
    {}
    int getminGodKor();
    void setminGodKor(int min);
    void info();
    ~Rucni();
};

让子类默认构造函数调用父类默认构造函数,并创建另一个带参数的子类构造函数来调用父类对应的子类构造函数:

#include <string>
using std::string;

class Alat
{
protected:
    string ime;
    int serBr;
    int cena;
public:   
    void setIme(string i)
    {
        ime = i;
    }
    string getIme()
    {
        return ime;
    }
    void setSerBr(int sb)
    {
        serBr = sb;
    }
    int getSerBr()
    {
        return serBr;
    }
    void setCena(int c)
    {
        cena = c;
    }
    int getCena()
    {
        return cena;
    }
    Alat()
    {
    }
    Alat(string i, int sb, int c) : ime(i), serBr(sb), cena(c)
    {
    }
    ~Alat()
    {
    }
};

class Rucni : public Alat
{
protected:
    int minGodKor;
public:    
    Rucni() // implicit call of the parent default constructor
    {
    }
    Rucni(string i, int sb, int c) : Alat(i, sb, c) // explicit call of the corresponding parent constructor
    {
    }
    int getminGodKor()
    {
        return minGodKor;
    }
    void setminGodKor(int min)
    {
        minGodKor = min;
    }
    ~Rucni()
    {
    }
};

int main()
{
    Rucni r;
    return 0;
}