将派生类传递给定义的函数以获取基类参数

时间:2015-10-30 16:29:31

标签: c++

如果我有基类和派生类,例如:

class Base {
protected:
  int a;
public:
  void setA(int);
  void getA(int);
}

class Derived : public Base {
private:
  int b;
public:
  void doThing();
}   

然后是第三个使用基类的附加类:

class OtherClass {
public:
  Base doClassThing(Base*, Base*);
}

将派生类传递给定义为返回基类并将基类作为参数的函数的最佳方法是什么。像这样:

Derived *x = new Derived();
Derived *y = new Derived();

doClassThing(x, y);

我会使用类型转换传递对象吗?或者我应该在首次创建对象时输入对象?

1 个答案:

答案 0 :(得分:1)

回答你的两个问题:

  • 在首次创建对象时,您不会对其进行投射。

  • 打电话时无需投票;您无需修改​​问题中的代码。

相关问题