Ich denke, dass Java möglich ist, das Objekt der Kindklasse durch das Objekt der Elternklasse zu ersetzen. Ich möchte es in C++ machen.Wie das Objekt der untergeordneten Klasse zurückgegeben wird, wenn der Funktionsrückgabetyp die übergeordnete Klasse ist?
Ich versuche es wie folgt zu tun. Allerdings habe ich "Fehler: Rückgabetyp 'Essen' ist eine abstrakte Klasse" Fehler. Wie kann ich es reparieren?
Vor es funktioniert:
#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;
}
Nach Klassendefinition weggelassen. es nicht funktioniert:
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;
}
Update 1
Dank vieler Ratschläge, war mein Problem gelöst. Ich muss C++ 11 verwenden, also verwende ich unique_ptr statt 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 über Boost-Bibliothek erwähnt. Ich werde ein Update veröffentlichen, nachdem ich Boosts intelligenten Zeiger als meine Notiz verwenden kann.
Also haben Sie 2 Fragen oder eine? : P – gsamaras
'pFood' ist ein Zeiger. 'getFoodObject' gibt ein Objekt und keinen Zeiger zurück. In Java sind fast alles implizite Zeiger. Also sollten Sie auch mit Zeigern arbeiten, um das zu erreichen, was Sie wollen – Alexey
Post echten Code! '' strcmp (type, "fruit") '' wird nicht mit '' string type'' kompiliert. –