[英]C++ functions that return objects
How can I write a function that 我该如何编写一个函数
returns an object of a different class each time 每次返回不同类别的对象
depending on its parameters ? 根据其参数?
ex 前
class pet{....};
class cat:public pet {.....};
class dog:public pet {.....};
cat_or_dog make pet (int a){
if (a) { cat b; return b;}
else { dog b; return b;}};
I assume you are looking to take advantage of polymorphism. 我假设您正在寻求利用多态性。
Your function will need to return a pointer to a pet
, preferably a smart pointer like std::unique_ptr<pet>
: 您的函数将需要返回一个指向
pet
的指针,最好是一个像std::unique_ptr<pet>
这样的智能指针:
#include <memory>
class pet{
public:
virtual ~pet(){};
};
class cat:public pet {};
class dog:public pet {};
std::unique_ptr<pet> makePet(int a){
if (a)
return std::unique_ptr<pet>(new cat);
else
return std::unique_ptr<pet>(new dog);
}
int main() {
auto pet = makePet(2);
}
And your pet
should have a virtual destructor in order to clean up properly. 而且您的
pet
应该有一个虚拟的析构函数以便正确清理。
@Chris Drew's answer works if your classes both inherit from the same base class. 如果您的类都继承自同一基类,则@Chris Drew的答案有效。 However, if they don't there is another option.
但是,如果没有,则还有另一种选择。 You can use
std::optional
to optionally return an object. 您可以使用
std::optional
可选地返回一个对象。 You can use it like this 你可以这样使用
std::pair<std::optional<cat>, std::optional<dog>> makePet(int a)
{
std::pair<std::optional<cat>, std::optional<dog>> pet;
if(a)
pet.first = cat();
else
pet.second = dog();
return pet;
}
You can then check which pet is there by checking the std::optional
within the pair like this 然后,您可以通过检查像这样的配对中的
std::optional
来检查哪个宠物在那里
std::pair<std::optional<cat>, std::optional<dog>> pet = makePet(i);
if (pet.first)
{
//Do things with cat
}
else
{
//Do things with dog
}
Be warned though that std::optional
is still experimental so it might not be implemented by your compiler. 请注意,尽管
std::optional
仍处于实验阶段,因此您的编译器可能未实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.