【问题标题】:Calling a method from a derived class object that returns a base class pointer从派生类对象调用返回基类指针的方法
【发布时间】:2017-10-28 03:58:39
【问题描述】:

我对一些 c++ OOP 概念有误解,例如如果我有一个 base 类返回指向同一类的对象的指针,请说:

class base{
public:
    int baseVal;
    base* foo(){
        return new base;
    }
}

还有一个继承方法foo()derived类:

class derived : public base{
public:
    int derivedVal;
    //some other members
}

我的问题是“当我从 derived 对象调用方法 foo() 时会发生什么?有什么方法 - 而不是覆盖 - 让它返回 derived 而不是 base 的对象?”例如:

int main(){
    derived obj1;
    derived * obj2P = obj1.foo();
    cout << obj2P->derivedVal << endl;
    return 0;
}

我该如何处理这样的事情?

【问题讨论】:

  • 为什么不想覆盖?覆盖是获得这种效果的确切方法。
  • 重写我的意思是写一个新方法——同名——返回一个指向derived对象的指针。
  • 好吧,如果 foo 没有在 base 中声明为 virtual,而你在 derived 中写了另一个 foo,那将是隐藏的,而不是技术上的覆盖。但我仍然不知道你到底想做什么。
  • 不,你不能那样做...derivedVal 是派生的数据成员而不是基数。
  • 可能是一个 x/y 问题。你到底想做什么?这样,人们就可以根据实际情况提出解决方案,而不仅仅是抽象地评论某事是否可行,何时可能不是一个好主意,甚至是你想要的。另外,以防万一,谷歌克隆模式。

标签: c++ oop inheritance


【解决方案1】:

您可以使用模板化的基类来实现您想要的。

template<typename derived_t>
class base {
public:
  derived_t* foo() {
    return new derived_t;
  }
};

class derived : public base<derived> {
public:
  int derivedVal;
  //some other members
};

另见 CRTP 模式。

虽然返回一个拥有的原始指针通常是不好的做法,你应该更喜欢返回像unique_ptr这样的智能指针:

template<typename derived_t>
class base {
public:
  std::unique_ptr<derived_t> foo() {
    return std::make_unique<derived_t>();
  }
};

【讨论】:

  • 不确定 CRTP 模式是否适合 OP。
猜你喜欢
  • 2014-02-15
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 2013-09-23
  • 2013-03-28
  • 1970-01-01
  • 2016-07-03
  • 1970-01-01
相关资源
最近更新 更多