[英]If you want to return a member by reference, what is the best way to define it?
[英]What is the correct way to have a member function return type be a superclass of the actual object you want to return?
讓成員函數返回類型成為您要返回的實際對象的超類的正確方法是什么?
Clang tidy 警告我返回subClassA
或subClassB
會丟棄我對myMethod
覆蓋。 我也沒有得到任何輸出 - 大概是因為我不小心丟棄了覆蓋的myMethod
。
#include <iostream>
using namespace std;
class SuperClass {
public :
SuperClass() {
cout << "I'm the superclass" << endl;
};
virtual std::string myMethod();
};
class SubClassA : public SuperClass {
public:
SubClassA() : SuperClass() {
cout << "I'm subclass A" << endl;
}
std::string myMethod() override {
return "A";
}
};
class SubClassB : public SuperClass {
public:
SubClassB() : SuperClass() {
cout << "I'm subclass B" << endl;
}
std::string myMethod() override {
return "B";
}
};
class Client {
private:
std::string which;
SuperClass letterFactory(){
if (which == "A") {
SubClassA subClassA;
return subClassA;
} else if (which == "B") {
SubClassB subClassB;
return subClassB;
} else {
throw std::invalid_argument("Bad");
}
}
public:
explicit Client(std::string &which) : which(which) {
letterFactory();
};
};
int main() {
Client client();
return 0;
};
您不會返回您在letterFactory
中創建的派生類對象。 相反,您將基類對象作為您在函數中聲明的派生類對象的切片副本返回。
在這個返回的對象上調用myMethod
將調用SuperClass
的實現,因為它的最派生類型將是SuperClass
。
多態只適用於指針和引用。 如果您希望您的類返回任一派生類類型,則它不能按值返回。 您可以返回一個指向動態分配實例的指針:
std::unique_ptr<SuperClass> letterFactory(){
if (which == "A") {
return std::make_unique<SubClassA>();
} else if (which == "B") {
return std::make_unique<SubClassB>();
} else {
throw std::invalid_argument("Bad");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.