[英]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.