我试图在派生类中初始化一个基类变量,但我得到了一个错误:
"this declaration has no storage class or type specifier"
我一直在修补 Visual Studio 中的 C++ 继承和派生类。我用 protected
变量创建了主类“Food
”,并想派生一个类“Bread
”
当尝试初始化“Bread
”中的上述变量时,VS 给出错误。我觉得这是一个非常简单的问题,但我不知何故错过了。
#include <string>
using namespace std;
class Food
{
protected:
string name;
int cost;
int calories;
public:
Food(string name, int cost, int calories) {
}
};
class Bread : public Food
{
private:
name = "";
cost = 5;
calories = 200;
public:
};
除了要初始化的 Bread
变量:
名称
为“”
(空),费用
为“5
”,卡路里
作为“200
”。
输出是一个错误:
"this declaration has no storage class or type specifier"
最佳答案
I'm trying to initialize a base class variable in a derived class!
首先,在您提供的基类Food
的构造函数中初始化成员。
Food(std::string name, int cost, int calories)
: name{ name }
, cost{ cost }
, calories{ calories }
{}
然后,需要在constructor member initializer list中初始化基类成员派生类 Bread
的 :
class Bread : public Food
{
public:
Bread()
:Food{ "", 5, 200 }
{}
};
这将初始化 Food
成员
name = ""
cost = 5
calories = 200
关于c++ - 如何修复给出 'declaration has no storage class or type specifier' 错误的派生类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56519303/