yukangliu 2016-09-14 11:37 采纳率: 66.7%
浏览 1292
已采纳

C++纯虚函数问题请指教

#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;
}

  • 写回答

3条回答 默认 最新

  • weak_ptr 2016-09-14 12:26
    关注

    上代码。

     #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 返回的是指针。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波