我的课如下:

Class A
{
   virtual int doSomethingCool() = 0;
};

Class B : public A
{
  int doSomethingCool();
};

现在问题就好了,我有一组依赖于A作为接口(interface)的类。我需要为其中一个派生类更改函数的原型(prototype)。即我需要传递一个参数。
Class C: public A
{
 int doSomethingCool(int param);
};

有什么建议我可以实现这一目标吗?

最佳答案

不,您不需要将其添加到基类。

class A
{
public:
  virtual int doSomethingCool() = 0 {}
};

class B : public A
{
public:
  int doSomethingCool() {return 0;}
};

class C: public A
{
private:
  int doSomethingCool(); // hide base class version!
public:
  int doSomethingCool(int param) {return param;}
};

如果通过基类指针完成操作,仍然可以调用doSomethingCool():
C c;
//c.doSomethingCool (); // doesn't work, can't access private member
c.doSomethingCool (42);
A &a = c;
a.doSomethingCool ();
//a.doSomethingCool (42); // doesn't work, no member of A has that signature

关于c++ - C++继承问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4284984/

10-11 23:51