如何修复派生 class 给出 'declaration has no storage class or type specifier' 错误?

How to fix derived class giving 'declaration has no storage class or type specifier' error?

我正在尝试在派生 class 中初始化基 class 变量,但我收到错误消息:

 "this declaration has no storage class or type specifier"

我一直在修补 Visual Studio 中的 C++ 继承和派生 classes。我用 protected 变量制作了主 class “Food” 并想导出一个 class “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 的变量: name 作为 ""(空),cost 作为“5”,calories 作为“200”。

输出是一个错误:

"this declaration has no storage class or type specifier"

I'm trying to initialize a base class variable in a derived class!

首先,在您提供的 class Food 的构造函数中初始化成员。

Food(std::string name, int cost, int calories)
    : name{ name }
    , cost{ cost }
    , calories{ calories }
{}

然后,需要在派生classBreadconstructor member initializer list中初始化基础class成员:

class Bread : public Food 
{
public:
    Bread()
        :Food{ "", 5, 200 }
    {}
};

这将初始化 Food 个成员

name = ""
cost = 5
calories = 200