开发者

select derived class file global variable by base class virtual function

This is a common problem I am facing. I am intended to write a derived class for an existing code. Let me provide the code snippet (just example):

Base_class_file:

const int addr=0xA;

Base_class::Read()
{
  return *addr;
}

Please note, the addr variable is a global variable in base class file. Now, I am writing the derived class because to change some functionality and also to change the addr. I would like to re-use the Read() method, and just mention the new addr(let's s开发者_如何学Goay 0xB) in the derived class file. Since this variable is a global variable, how do I mention to the base class Read() method to use the addr=0xB than the 0xA ??

Your help is greatly appreciated.


How about....

virtual int & GetTheGlobalVariable() const {return addr;}

and then overriding that method in the subclass to return a different result?


You override it in the derived class and have it return 0xB. Of course this works only if the base class Read method is declared virtual.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜