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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料