ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

c – 如何在继承的类上初始化静态变量?

2019-09-02 15:08:23  阅读:153  来源: 互联网

标签:static-variables c inheritance initialization


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

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

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;

我的问题是:我无法在TenisBall和OtherBall类上设置静态值,如果我在最后两行代码中更改了TenisBall和OtherBall for 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;
};

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

invalid character ‘_’ in Bundle Identifier at column 22. This string must be a uniform type identifier (UTI) that contains only alphanumeric (A-Z,a-z,0-9), hyphen (-), and period (.) characters.

解决方法:

你尝试的是不可能的.一旦在类中声明了一个静态变量,这个类只有一个变量,甚至派生类也不能改变它(所以你不能改变Ball :: file来为TennisBall做一些不同的事情).

最简单的解决方法可能是将Ball :: file更改为虚拟函数(返回字符串或字符串以及甚至可以是类或函数静态的函数),您可以在派生类中重写它.

标签:static-variables,c,inheritance,initialization
来源: https://codeday.me/bug/20190902/1791654.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有