[英]How do I access a private constructor in a class from the main function in C++?
我有一個程序,我有一個名為Flower的超類和Rose,Lily,Jasmine子類。
花保護成員用2個變量描述花的特征和具有getter函數的公共成員和一個純虛函數(稱為字符串getColor())打印子類花的顏色。 它還有一個公共成員函數,可以打印每個花的特征(void printFlower(string name))。
我正在嘗試為Rose,Lily和Jasmine實現類,我不得不在類中使用public access修飾符。 因此,類中的所有內容都必須是受保護的或私有的(甚至是構造函數)。 我知道Rose,Lily和Jasmine公開繼承了父類Flower。
在我的主要功能中,我有這個:
int main(){
Rose rose;
Flower * pointer = &rose;
rose.printFlower("red");
Lily lily;
pointer = &lily;
lily.printFlower("white"); // not sure what color lilies are
Jasmine jas;
pointer = &jas;
jas.printFlower("orange");
return 0;
}
我的任務是不在Rose,Lily和Jasmine類中使用公共訪問修飾符,但如果我願意,我可以公開繼承Flower。 那么,有沒有辦法使用私有構造函數(使用Flower作為朋友)或類似的東西來實現這一目標?
編輯:我意識到我提供的信息很少,所以我在這里編輯問題。 以下是Flower超級班的宣言,我無法改變。
class Flower{
protected:
bool isPopular;
bool isThorny;
public:
Flower(bool isPopular, bool isThorny){
this->isPopular = isPopular;
this->isThorny = isThorny;
}
bool getIsPopular(){
return this->isPopular;
}
bool getIsThorny(){
return this->isThorny;
}
virtual string getColor() = 0;
void printFlower(string name){
cout << "A " << name << " has '" << this->getColor() << "' color and is "
<< (this->getIsThorny()?"":"not ") << "thorny, and is " << (this->getIsPopular()?"":"not ")
<< "very popular." << endl;
}
};
我的任務基本上是圖像中的以下內容: 用於聲明派生類的任務
該任務將運行main並在從main調用時打印printFlower函數。 我唯一的限制是我不能在Rose,Lily和Jasmine的類聲明中使用公共訪問修飾符,但我可以並且公開繼承花。 即。 Rose Rose:public Flower(){}我有沒有辦法讓Rose,Lily和Jasmine成為私人或受保護的?
你顯然被引導到對工廠模式的某種看法。 解決方案是在Flower
定義一個工廠函數來進行實例化。
我將展示如何做到這一點。 為了說明為什么這可能有用,我將使工廠成為一個簡單的轉換器,從運行時參數到編譯時類型:
class Flower
{
public:
virtual ~Flower() = default;
static std::unique_ptr<Flower> create(const std::string &species)
{
std::unique_ptr<Flower> result;
if (species == "rose")
{
result = std::make_unique<Rose>();
}
else if (species == "lily")
{
result = std::make_unique<Lily>();
}
else
{
throw std::invalid_argument("No such flower");
}
return result;
}
};
class Rose : public Flower
{
friend Flower;
Rose() = default;
};
class Lily : public Flower
{
friend Flower;
Lily() = default;
};
int main(int argc, char **argv)
{
auto rose = Flower::create("rose");
auto lily = Flower::create("lily");
auto whatTheUserRequested = Flower::create(argv[1]);
}
使用像這樣的工廠功能
class FlowerFactory
{
Flower* getFlower(string flowerName)
{
if(flowerName == "Rose")
{
return new Rose();
}
if(flowerName == "Lily")
{
return new Lily();
}
if(flowerName == "Jasmine")
{
return new Jasmine();
}
}
}
//Base class
class Flower
{
};
class Jasmine : public Flower
{
//other things here..
friend FlowerFactory;
};
class Rose : public Flower
{
//other things here..
friend FlowerFactory;
};
class Lily : public Flower
{
//other things here..
friend FlowerFactory;
};
您的指示是不使用訪問說明符,還是您的所有成員都不是私有的? 如果是前者,則可以使用struct
而不是class
來默認獲取公共訪問權限。 例如:
struct Rose : Flower {
Rose() : Flower(...) {}
string getColor() const override { return "red"; }
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.