简体   繁体   中英

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. I currently have this working by using a static double within a base class with pure virtual functions to set the value:

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. I know I can't define a static member variable more than once, and using the headers is giving me multiple initialization errors. 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:

double base::shared_value = 0;

Now any child class can access that value including editing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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