基类和派生类中的构造函数
Constructor in base and derived class
程序工作,但我不确定什么是错误的构造函数,因为每次程序运行它得到这个错误"警告:基类'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;
}
相关文章:
- 如何委托派生类使用其父构造函数?
- 如果基类包含双指针成员,则派生类的构造函数
- C++:为什么无法在派生类中访问受保护的构造函数?
- C++派生的类构造函数
- 添加自定义析构函数时,Move 构造函数在派生类中消失
- 在没有默认构造函数的情况下创建的派生对象
- 派生类(构造函数具有参数)和基类(构造函数缺少参数)之间没有可行的转换
- 如何在派生构造函数中多次构造基类
- C++(控制台)构造函数和派生类
- 为什么为派生类定义复制构造函数需要定义基类的默认构造函数?
- 在dynamic_pointer_cast后调用派生类的构造函数
- 如何使用函数(而不是构造函数)将派生类对象分配给基类指针
- 将派生类的构造函数声明为父类的友元
- 如何为具有私有成员的派生类实现移动构造函数
- 使用回调函数从构造函数调用虚拟/派生方法的替代方法?
- 在派生自线程类的构造函数中传递字符串
- C++ 为什么要将对基类的引用传递给派生类的构造函数
- C++将派生类的const值传递给基意外行为的构造函数
- 在模板派生类中继承具有类型别名的构造函数
- 正在调用基方法,而不是从构造函数派生方法