简体   繁体   English

从返回基类指针的派生类对象调用方法

[英]Calling a method from a derived class object that returns a base class pointer

I have a misunderstanding with some c++ OOP concepts, for example If I have a base class that returns a pointer to an object of the same class, say:我对一些 C++ OOP 概念有误解,例如,如果我有一个base类返回指向同一类对象的指针,请说:

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

and a derived class that inherits method foo() :以及继承方法foo()derived类:

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

My problem is "What will happen when I call the method foo() from a derived object? are there any way -instead of overriding- to make it return an object of derived not base ?"我的问题是“当我从derived对象调用方法foo()时会发生什么?有什么方法 - 而不是覆盖 - 让它返回一个derived对象而不是base ?” for example:例如:

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

How may I handle something like that?我该如何处理这样的事情?

You can achieve what you want with a templated base class.您可以使用模板化基类实现您想要的。

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
};

See also the CRTP pattern.另请参阅 CRTP 模式。

Although, it is generally bad practice to return an owning raw pointer and you should prefer to return smart pointer like unique_ptr :虽然,返回拥有的原始指针通常是不好的做法,您应该更喜欢返回像unique_ptr这样的智能指针:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从空指针转换为基础对象调用派生类方法 - Calling a Derived Class method from a Void Pointer cast to a Base Object 将方法添加到派生类并从基本指针调用它 - adding method to derived class and calling it from base pointer 对基类的对象的派生类的调用方法 - Calling method of derived class on object of base class 从派生类对象调用基类方法时出错。 基类和派生类都是模板化的 - Error calling a base class method from a derived class object. Both base and derived classes are templated 从派生构造函数调用基类方法 - Calling base class method from derived constructor 从派生类调用base方法 - Calling base method from derived class 在将基类指针类型转换为派生类指针后从基类指针调用派生类函数 - Calling Derived class function from a Base class pointer after typecasting it to Derived class pointer 通过绑定到已删除的派生object的基指针class调用虚方法有什么效果 - What is the effect of calling a virtual method by a base class pointer bound to a derived object that has been deleted 从基类指针派生的类方法:一些替代方法? - Derived class method from base class pointer : some alternatives? 从派生类方法设置基础对象 - Setting base object from derived class method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM