如何初始化抽象类的静态成员变量 [英] How to initialize static member variable of abstract class

查看:224
本文介绍了如何初始化抽象类的静态成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我有这样的情况.

Hi,
I have scenario like this.

class Books
{
protected:
   static int BookId;
   int    b;
   ;
public:
   void Init () = 0;
   SetVal (int val);
   ;
}

class Novel : public Books
{
public:
   Init (int val) {b = val}
}



我想将int BookId初始化为0.如何有效地做到这一点而又不破坏OOP概念?



I want to initialize int BookId to 0. How this can be done in efficient way without killing OOP concept ?

推荐答案

允许您使用一个包含该类的books.h文件图书申报,
您需要一个CPP文件(books.cpp可以是很好的文件)
Admitting you he a books.h file containing the class Books declaration,
you need a CPP file (books.cpp can be good) that does
#include "books.h"
int Books::BookId = 0;



它与 venkatmakan [ ^ ]在他的解决方案中起作用,但是如果更多的"CPP"文件包含"books.h"文件,则这种方式将导致多重定义"链接器错误.



It is basically the same as venkatmakan [^]did in his solution, but that way result in a "multiple definition" linker error, in case the "books.h" file is included by more "CPP" files.


给出错误?
will this give error?
class Books
{
protected:
   static int BookId;
   int    b;
public:
   virtual void Init () = 0; //syntax is corrected
   int SetVal (int val);
};
int Books::BookId = 0;


构造函数?

显然,我需要写更多的内容来发布我的答案.
A constructor ?

Apparently I need to write more, to post my answer.


这篇关于如何初始化抽象类的静态成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆