gpt4 book ai didi

c++ - 抽象工厂模式客户端代码

转载 作者:行者123 更新时间:2023-11-28 07:16:06 24 4
gpt4 key购买 nike

我正在尝试为 abs 工厂编写我的客户端代码,但我被卡在了客户端代码中。我无法通过 Factorymaker.getFactory("Bshell"); 实例化任何 Bshell 代码在没有客户端代码的情况下编译

(我是stackoverflow的新手。我的iostream在我的代码中是正常的。)

#include <iostream> 

using namespace std;
//This is the abstract product.
class Shell {

public:
virtual void printShell(){ cout << "I am the abstract product\n"; }
};
class Bshell : public Shell {

public:
Bshell();
Bshell(string arg){ cout << "I am " << arg << endl; }
void printShell(){ cout << "I am Bshell\n"; }
};
class Cshell : public Shell {

public:
Cshell();
Cshell(string arg){ cout << "I am " << arg << endl; }
void printShell(){ cout << "I am Cshell\n"; }
};
class Kshell : public Shell {

public:
Kshell();
Kshell(string arg){ cout << "I am " << arg << endl; }
void printShell(){ cout << "I am Kshell\n"; }
};
//This is the abstract factory.
class ShellFactory {

public:
virtual Shell* createBshell();
virtual Shell* createCshell();
virtual Shell* createKshell();
};
//Concrete factories
class BShellFactory : public ShellFactory {

public:
Shell* createBshell(){ return new Bshell("Bshell"); }
};
class CShellFactory : public ShellFactory {

public:
Shell* createCshell(){ return new Cshell("Cshell"); }
};
class KShellFactory : public ShellFactory {

public:
Shell* createKshell(){ return new Kshell("Kshell"); }
};
//indirectly instantiating factories
class Factorymaker {

private:
ShellFactory *sf = NULL;
public:
ShellFactory* getFactory(string choice){

if (choice == "Bshell"){ sf = new BShellFactory(); }
else if (choice == "Cshell"){ sf = new CShellFactory(); }
else if (choice == "Kshell"){ sf = new KShellFactory(); }
return this->sf;
}
};
int main()
{
Factorymaker *fmaker = new Factorymaker();
ShellFactory *sf = fmaker.getFactory("Bshell");
Bshell bshellproduct = sf.createBshell();
return 0;
}

最佳答案

fmakersf 是指针,所以使用 -> 而不是 . 来访问它们的成员。

sf->createBshell()的返回类型是Shell*,所以应该是bshel​​lproduct的类型。

您的编译器应该已经告诉您所有这些。

关于c++ - 抽象工厂模式客户端代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20214179/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com