如何初始化继承类的静态变量?

Jal*_*orc 4 c++ inheritance initialization static-variables

我正在尝试创建一个“父”类,它为所有继承的类提供通用的构造函数和参数类型。继承的变量之间唯一发生变化的是一些静态变量的值。

实现这一目标的最佳方法是什么?这是我目前的尝试:

class Ball {
  public:
    virtual ~Ball();
    Ball ();

  protected:
    static string file;
    static int size;
    node shape;
};

class TenisBall: public Ball {};
class OtherBall: public Ball {};

Ball::Ball () {
  shape = // do something with file and size
};

Ball::~Ball () {
  delete shape;
};

string TenisBall::file = "SomeFile";
int TenisBall::size = 20;

string OtherBall::file = "OtherFile";
int OtherBall::size = 16;
Run Code Online (Sandbox Code Playgroud)

TenisBall我的问题是:我无法在and类上设置静态值OtherBall,编译器仅接受我在最后两行代码中更改TenisBalland OtherBallfor的情况。Ball我怎样才能做到这一点?这是最好的方法吗?

编辑:

根据提供的答案,我决定尝试使用虚拟函数来实现它。到目前为止,这是我的代码:

class Ball {
  public:
    Ball () {
      shape = // do something with getSize and getFile
    };

    ~Ball () {
      delete shape;
    };

  protected:
    virtual string getFile(){ return "Fake"; };
    virtual int getSize(){ return 10; };

    node shape;
};

class TenisBall: public Ball {
  int getSize() { return 16; };
  string getFile() { return "TennisBall.jpg"; };
};

int main() {
  TenisBall ball;
  return 1;
};
Run Code Online (Sandbox Code Playgroud)

但是,虽然我的编辑器(xCode)没有给出任何错误,但在尝试编译时,llvm 给出了以下错误:

第 22 列的捆绑标识符中存在无效字符“_”。该字符串必须是仅包含字母数字 (AZ,az,0-9)、连字符 (-) 和句点 (.) 字符的统一类型标识符 (UTI)。

jpa*_*cek 7

你尝试的事情是不可能的。一旦在类中声明了静态变量,该类就只有一个变量,甚至派生类也无法更改这一变量(因此您无法更改Ball::file为执行不同的操作,TennisBall无论这意味着什么)。

最简单的解决方法可能是更改为可以在派生类中重写的Ball::file虚函数(返回string或甚至可能是类或函数静态的东西)。string&


jro*_*rok 5

如果您希望每个派生类都有自己的静态变量,您可以将基础类作为模板并使用CRTP

template<typename T>
class Ball {
    static int size;
};

template<typename T> int Ball<T>::size = 0;

class TennisBall : public Ball<TennisBall> {

};

template<> int Ball<TennisBall>::size = 42;
Run Code Online (Sandbox Code Playgroud)