gpt4 book ai didi

c++ - 类工厂创建派生类 C++

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

我目前正在学习使用 C++ 的类工厂模式。我在尝试实现工厂时一直出错。假设我有一个抽象类和两个派生类。我想让工厂做的是像这样创建基类的新对象: Ball *sc = new SoccerBall();我不确定如何实现这一点,我已经尝试过但无济于事。我需要修复什么?

class Ball
{
public:
Ball();
virtual ~Ball();
virtual int getSize() const = 0;
virtual void setBallSize(int s) = 0;
virtual string ballManufacturer() const = 0;
protected:
int ballSize;
}
class Soccerball:public Ball
{
public:
Soccerball();
Soccerball(int size);
~Soccerball();
int getSize() const;
void setBallSize(int s);
string ballManufacturer() const;
}
class Soccerball:public Ball
{
public:
Soccerball();
Soccerball(int size);
~Soccerball();
int getSize() const;
void setBallSize(int s);
string ballManufacturer() const;
}
class Basketball:public Ball
{
public:
Basketball();
Basketball(int size);
~Basketball();
int getSize() const;
void setBallSize(int s);
string ballManufacturer() const;
}
class BallFactory
{
public:
Ball* createBall(string s)
{
if(s == "Soccer")
{
return new Soccerball(5);
}
if(s == "Basket")
{
return new Basketball(6);
}
}
}

最佳答案

这就是您的代码的工作方式,但在上面发布问题时,您应该提供“简短的自包含正确代码”,以便人们轻松理解您的问题。

#include <iostream>

using namespace std;

class Ball
{
public:

Ball()
{
cout<<"Ball ctr"<<endl;
}

virtual ~Ball()
{

}
virtual int getSize() const = 0;
virtual void setBallSize(int s) = 0;
virtual string ballManufacturer() const = 0;

protected:
int ballSize;
};

class Soccerball:public Ball
{
public:

Soccerball()
{
cout<<"create Default Soccer Ball "<<endl;
}

Soccerball(int size)
{
cout<<"create Soccer Ball "<<size<<endl;
}

~Soccerball()
{

}

int getSize() const
{
return ballSize;
}

void setBallSize(int s)
{
ballSize = s;
}

string ballManufacturer() const
{
return "";
}
};

class Basketball:public Ball
{
public:

Basketball()
{
cout<<"create default Baseket Ball "<<endl;
}

Basketball(int size)
{
cout<<"create Baseket Ball "<<size<<endl;
}

~Basketball()
{

}

int getSize() const
{
return ballSize;
}

void setBallSize(int s)
{
ballSize = s;
}

string ballManufacturer() const
{
return "";
}
};

class BallFactory
{
public:
//Factory method
static Ball* createBall(string s)
{
if(s == "Soccer")
{
return new Soccerball(5);
}
if(s == "Basket")
{
return new Basketball(6);
}
}
};

int main()
{
Ball* ptr = BallFactory::createBall("Soccer");

return 0;
}

但您还需要了解工厂设计模式的工作原理、同名虚拟构造函数的创建方式以及使用参数化工厂的原因。或者你可以使用模板工厂。

关于c++ - 类工厂创建派生类 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30660376/

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