#include
#include
using namespace std;
class Toy {
public:
virtual void talk() const=0;
};
class Dog: public Toy {
// Write your code here
public:
void talk()
{
cout<<"Wow"<<endl;
}
};
class Cat: public Toy {
// Write your code here
public:
void talk()
{
cout<<"Meow"<<endl;
}
};
class ToyFactory {
public:
/**
* @param type a string
* @return Get object of the type
/
Toy getToy(string& type) {
// Write your code here
if(type=="Dog")
{
Dog d;
return d;
}
if(type=="Cat")
{
Cat *c;
return c;
}
}
};
int main()
{
string type;
type="Dog";
ToyFactory tf = new ToyFactory();
Toy* toy = tf->getToy(type);
toy->talk();
return 0;
}
上代碼。
#include <iostream>
#include <string>
#include <memory>
using namespace std;
class Toy {
public:
virtual void talk() const = 0;
};
class Dog : public Toy {
// Write your code here
public:
void talk() const { cout << "Wow" << endl; }
};
class Cat : public Toy {
// Write your code here
public:
void talk() const { cout << "Meow" << endl; }
};
class ToyFactory {
public:
/**
* @param type a string
* @return Get object of the type
*/
unique_ptr<Toy> getToy(string &type) {
// Write your code here
if (type == "Dog") {
return unique_ptr<Dog>(new Dog);
}
if (type == "Cat") {
return unique_ptr<Cat>(new Cat);
}
}
};
int main() {
string type;
type = "Dog";
ToyFactory * tf = new ToyFactory();
unique_ptr<Toy> toy = tf->getToy(type);
toy->talk();
return 0;
}
主要是以下問題:
1,Dog/Cat類型talk方法的簽名和Toy的talk方法簽名不一致,Toy的簽名是void talk() const
,注意const
。
2,getToy方法不應該返回Toy類型,因為Toy是一個不能實例化的抽象類。返回Toy類型的指針,應當return new Dog;
和return new Cat;
,窩這裡使用了unique_ptr,不用在意。
3,ToyFactory tf = new ToyFactory
應該是ToyFactory *tf
,注意new 返回的是指針。