【问题标题】:Can I use inherited class pointers just as parent's?我可以将继承的类指针用作父类指针吗?
【发布时间】:2012-06-10 08:21:34
【问题描述】:

我的两个类:Parent 和 Child 是相同的(目前)并且具​​有相同的构造函数。

class Parent{
protected:
  string name;
public:
  Parent(string &n, vector <int> &v) {
  /* read n and v into vars */
};

class Child : public Parent {
public:
  Child(string &n, vector <int> &v) : Parent(n, v) {}
};
vector <int> val;
string nam, numb;
if(val[0] == 0) 
  Child* ptr = new Child(nam, val);
else
  Parent* ptr = new Parent(nam, val);

myMap.insert(Maptype::value_type(numb, ptr) );

将 Child* ptr 对象作为 Parent* ptr 对象传递是否合法?我听说它们具有相同的指针类型,所以应该没问题。那我为什么会得到 警告:未使用的变量“ptr” 警告:未使用的变量“ptr” 错误:未在此范围内声明“ptr” ? 我的程序仅适用于 Parent 类。我觉得我没有继承父母的权利。

【问题讨论】:

  • “父/子”不是 C++ 对象模型的一个很好的比喻,尤其是公共继承。 “基础”和“派生”要好得多。子类不是父类,但派生类在某种意义上是它们的公共基类的一个版本。

标签: c++ inheritance pointers constructor


【解决方案1】:

代码创建了两个单独的变量ptr,它们的作用域都非常有限。

考虑以下几点:

if(val[0] == 0) 
  Child* ptr = new Child(nam, val);
else
  Parent* ptr = new Parent(nam, val);

相当于:

if(val[0] == 0) {
  Child* ptr = new Child(nam, val);
} else {
  Parent* ptr = new Parent(nam, val);
}
// neither of the `ptr' variables is in scope here

这是修复代码的一种方法:

Parent* ptr;
if(val[0] == 0) 
  ptr = new Child(nam, val);
else
  ptr = new Parent(nam, val);

完成此操作后,您还需要确保Parent 具有虚拟析构函数。见When to use virtual destructors?

【讨论】:

【解决方案2】:

因为你只在 if 语句中声明了 ptr,所以试着在 if 语句的上方声明它,这样它可能就像 aix 的答案

【讨论】:

    猜你喜欢
    • 2011-02-11
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 2019-08-31
    • 2011-02-01
    • 2017-07-30
    • 1970-01-01
    相关资源
    最近更新 更多