c++ - 使用来自抽象基类 C++ 的变量的派生类

标签 c++ derived-class

我创建了一个抽象的 Light 类,其中包含所有灯光通用的字段和方法,现在我尝试从中派生一个 Directional Light

class Light
{
public:
    unsigned int strength;
    Color color;
    unsigned int index;

    Light() {};
    virtual ~Light() = 0;

    virtual pointLuminosity() = 0;
};

class DirectionalLight : public Light
{
public:
    Vector direction;
    DirectionalLight(const unsigned int &_strength, [...] ): strength(_strength), [...] {}
};

以上代码导致错误:

error: class 'DirectionalLight' does not have any field named 'strength'

Light 类派生所有字段并在 DirectionalLight 对象中使用它们的正确方法是什么?

最佳答案

除初始化列表外,您可以在任何地方使用强度。这行得通

DirectionalLight(const unsigned int &_strength) { strength = _strength; }

或者,您可以向 Light 添加一个构造函数

class Light
{
public:
    unsigned int strength;
    Light(unsigned s) : strength(s) {}
};

DirectionalLight(const unsigned int &_strength) : Light(_strength) {}

关于c++ - 使用来自抽象基类 C++ 的变量的派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51537406/

相关文章:

c++ - 基于线程数与执行时间关系的OpenMP并行编程

c++ - MSBuild 在针对不同配置运行时不必要地运行自定义生成工具

c++ - 将属性传递给基类的机制

c++ - Makefile 循环依赖被丢弃

c++ - DP - 计数硬币变化

c++ - 如何创建派生对象的 vector ?

c++ - 用派生类填充基类类型的二维 vector

c++ - 带有模板基类的静态成员定义

php - 派生属性未从父构造函数初始化

c++ - 基类构造函数错误