简体   繁体   English

static class header 文件的成员

[英]static class member for header files

I am working on a class hierarchy where I have a base class containing a value which needs to be shared with all other derived classes in my code.我正在研究 class 层次结构,其中我有一个基本 class 包含一个值,该值需要与我的代码中的所有其他派生类共享。 I currently have this working by using a static double within a base class with pure virtual functions to set the value:我目前通过在基础 class 中使用 static double 来实现此功能,并使用纯虚拟函数来设置值:

class base {
public:
    static double shared_value;
    virtual void set_value(double v) = 0;
    virtual double get_value() = 0;
};

class derived1 : public base {
public:
    void set_value(double v){ shared_value = v; }
    double get_value() { return shared_value; }
};

class derived2 : public base {
public:
    void set_value(double v){ shared_value = v; }
    double get_value() { return shared_value; }
};
etc...

The problem comes when I use header files with my code.当我将 header 文件与我的代码一起使用时,问题就出现了。 I know I can't define a static member variable more than once, and using the headers is giving me multiple initialization errors.我知道我不能多次定义 static 成员变量,并且使用标头会给我带来多个初始化错误。 I am not sure how else I can set and view this variable from any of the classes, any help will be hugely appreciated.我不确定我还能如何从任何类中设置和查看这个变量,任何帮助都将不胜感激。

You will need to define shared_value in a source file like so:您将需要在源文件中定义shared_value ,如下所示:

double base::shared_value = 0;

Now any child class can access that value including editing it.现在任何子 class 都可以访问该值,包括对其进行编辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM