1

我有一个基类,其中包含两个同名函数,一个以 avector<int>作为参数,一个以int. 这个想法是子类将定义自己的方法来处理 int,而基类将能够处理任一选项。但它目前无法编译。

class base {
public:
  virtual void toBeCalled(int i) const = 0;

  virtual void toBeCalled(std::vector<int> iVec) const
  {
    std::cout << "base::toBeCalled(vec<int>)" << std::endl;
  }
};  

class derived : public base {
public:
  virtual void toBeCalled(int i) const
  {
    std::cout << "derived::toBeCalled(int)" << std::endl;
  }
};

int main(int argc, char* argv[])
{
  derived d;
  std::vector<int> iVec;

  int i = 0;

  d.toBeCalled (i);
  d.toBeCalled (iVec);  //<< Compile error: Cannot convert from std::vector<int> to int

  return 0;
}

我可以通过在 main() 中使用基类对象来使其工作,base *d = new derived()但如果可能的话,我不想这样做,因为我想访问一些派生类函数。

4

4 回答 4

5

放入。using base::toBeCalled;_class derived

我很确定这是一个骗局,但我找不到,所以我不会详细说明。但是,当您覆盖(或重载)派生类中的函数时,您会隐藏该函数的所有基类版本。

此处讨论了该行为的基本原理:https ://stackoverflow.com/a/12036004/13005

于 2013-03-07T11:14:35.437 回答
3

你没有导致class derived从基础派生。

class derived: public base {
于 2013-03-07T11:15:05.077 回答
2

我假设您在此处复制代码时忘记指定基类。这是,而不是:

class derived {
public: // and so on

你有:

class derived : public base {
public: // and so on

为类定义方法时,这些方法会隐藏基类中的所有同名方法。在这种情况下,当您覆盖 method 时toBeCalled(),您是说该类derived将仅具有您指定的那些签名;基类中的任何其他签名都将被隐藏:

class derived : public base {
public:
  virtual void toBeCalled(int i) const
  {
    std::cout << "derived::toBeCalled(int)" << std::endl;
  }
  // void base::toBeCalled(std::vector<int> iVec) const is hidden and
  // cannot be accessed through this class
};

由于您不想在派生类中覆盖该方法的第二个版本,因此最好的方法是明确告诉编译器您要将该方法的所有基类版本导入(而不是隐藏)到派生类中班级。这是通过一个using子句完成的:

class derived : public base {
public:
  using base::toBeCalled; // Any version of method toBeCalled() not overriden here
                          // will now be taken from the base class
  virtual void toBeCalled(int i) const
  {
    std::cout << "derived::toBeCalled(int)" << std::endl;
  }
  // void base::toBeCalled(std::vector<int> iVec) const is taken
  // from the base class now
};
于 2013-03-07T11:27:18.987 回答
0

你可以这样称呼它,

  base.toBeCalled(iVec);  // here base is not base class name...it is reference to Parent Class 

另一种方式 -

class derived : base  {  // inherit base class
public:
  virtual void toBeCalled(int i) const
  {
    std::cout << "derived::toBeCalled(int)" << std::endl;
  }
};
于 2013-03-07T11:17:06.690 回答