[英]How to fix derived class giving 'declaration has no storage class or type specifier' error?
I am trying to initialize a base class variable in a derived class, but instead, I am given an error: 我正在尝试在派生类中初始化基类变量,但是却出现了一个错误:
"this declaration has no storage class or type specifier"
I have been tinkering with C++ inheritance and derived classes in Visual Studio. 我一直在修补C ++继承和Visual Studio中的派生类。 I made the main class " Food
" with protected
variables and want to derive a class " Bread
" 我使用protected
变量制作了“ Food
”主类,并想派生“ Bread
”类
When trying to initialize said variables in " Bread
," VS gives an error. 尝试在“ Bread
”中初始化所述变量时,VS给出错误。 I feel like this is a really simple problem that I somehow missed. 我觉得这是一个非常简单的问题,我以某种方式错过了。
#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:
};
I would except the variables of Bread
to be initialized: name
as ""
(empty), cost
as " 5
", calories
as " 200
". 我将要初始化的Bread
变量除外: name
为""
(空), cost
为“ 5
”, calories
为“ 200
”。
The output is instead an error: 输出而是错误:
"this declaration has no storage class or type specifier"
I'm trying to initialize a base class variable in a derived class! 我正在尝试在派生类中初始化基类变量!
First of all, initialize the members in the base class Food
's constructor, which you have provided. 首先,初始化您提供的基类Food
的构造函数中的成员。
Food(std::string name, int cost, int calories)
: name{ name }
, cost{ cost }
, calories{ calories }
{}
Then, you need to initialize the base class members in the constructor member initializer list of the derived class Bread
: 然后,您需要在派生类Bread
的构造函数成员初始化器列表中初始化基类成员:
class Bread : public Food
{
public:
Bread()
:Food{ "", 5, 200 }
{}
};
which will initialize the Food
members 这将初始化Food
成员
name = ""
cost = 5
calories = 200
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.