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

标签 c++ class c++11 inheritance member-initialization

我试图在派生类中初始化一个基类变量,但我得到了一个错误:

 "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/

相关文章:

android - 是否可以在扩展 View 的类中使用 Intent ?

java - 判断一个类是否是另一个类的字段

c++ - 两个字符串大小的差异

c++ - remove_pointer + typename 错误

c++ - 使用 std::array::size 实例化 std::array 时出错

c++ - 如果我在通知的条件变量上调用等待会发生什么

c++ - 在C++中获取2个空格之间的字符串

c++ - ARRAY - null,正元素的数量和正元素的总和

c++ - 什么是复制赋值运算符?

c++ - 具有相同类型的模板类的模板函数友元