【发布时间】:2017-06-23 14:26:12
【问题描述】:
我猜想Java 可以用子类的对象代替父类的对象。我想用 C++ 来做。
我正在尝试按照以下方式进行操作。但是,我收到“错误:返回类型 'Food' 是一个抽象类”错误。我该如何解决?
使用之前:
#include <iostream>
using namespace std;
class Food {
public:
virtual void SetPrice(int myprice) = 0;
int GetPrice() {
return price;
}
protected:
int price;
};
class Fruit : public Food {
public:
void SetPrice(int myprice) {
price = myprice - 20;
}
};
class Fish : public Food {
public:
void SetPrice(int myprice) {
price = myprice / 2;
}
};
int main(int argc, char* argv[])
{
Food *pFood;
Fruit myFruit;
Fish myFish;
if (strcmp(argv[1], "fruit") == 0) {
pFood = &myFruit;
} else {
pFood = &myFish;
}
pFood->SetPrice(100);
cout << pFood->GetPrice() << endl;
return 0;
}
After 类定义被省略。它不起作用:
Food getFoodObject(string type)
{
if (strcmp(type, "fruit") == 0) {
Fruit myFruit;
return &myFruit; // I don't want to write 2 lines. I want to return the above line. This is my another question...
}
Fish myFish;
return &myFish;
}
int main(int argc, char* argv[])
{
Food *pFood;
pFood = getFoodObject(argv[1])
pFood->SetPrice(100);
cout << pFood->GetPrice() << endl;
return 0;
}
更新 1
多亏了很多建议,我的问题得到了解决。我需要使用 c++11,所以我使用 unique_ptr 而不是 make_unique。
std::unique_ptr<Food> getFoodObject(string type)
{
if (type == "fruit") {
return std::unique_ptr<Fruit>(new Fruit);
}
return std::unique_ptr<Fish>(new Fish);
}
int main(int argc, char* argv[])
{
std::unique_ptr<Food> pFood = getFoodObject(argv[1]);
pFood->SetPrice(100);
cout << pFood->GetPrice() << endl;
return 0;
}
@dlasalle 提到了 Boost 库。在我可以使用 Boost 的智能指针作为我的笔记之后,我会发布更新。
【问题讨论】:
-
那么您有 2 个问题还是 1 个问题? :P
-
pFood是一个指针。getFoodObject返回一个对象,而不是指针。在 Java 中,几乎所有东西都是隐式指针。所以你也应该使用指针来实现你想要的 -
发布真实代码!
strcmp(type, "fruit")不会与string type一起编译。 -
@manni66 该错误低于关于返回类型抽象性的错误。 OP 按降序修复错误似乎是合理的。
标签: c++ c++11 polymorphism