私は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;
}
した後、クラス定義が省略されています。それは動作しません。
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つの
おかげで多くのアドバイスに、私の問題が解決されました。私はmake_uniqueの代わりにunique_ptrを使うので、C++ 11を使う必要があります。
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つの質問がありますか? :P – gsamaras
'pFood'はポインタです。 'getFoodObject'はポインタではなくオブジェクトを返します。 Javaではほとんどすべて暗黙的なポインタです。だからあなたはあなたが望むものを達成するためにポインタで作業するべきです – Alexey
実コードを投稿してください! '' strcmp(type、 "fruit") ''は '' string type''でコンパイルされません。 –