//友元没有继承性,没有传递性,所以在animal中定义友元类是无效的
class animal{
public:
animal(){};
virtual ~animal(){};
};
class Cat:public animal
{
friend class animalFactory;
private:
Cat(){
}
private:
string m_name;
string m_color;
public:
void about()
{
cout<<"my name is "<<m_name<<",my color is "<<m_color<<endl;
}
~Cat() override{
}
};
class Dog:public animal{
friend class animalFactory;
private:
Dog()
{
}
private:
string m_name;
string m_color;
int m_age;
public:
~Dog() override{
}
void about() const{
cout<<"i am a dog,my name is "<<m_name<<",my color is"<<m_color<<",i am "<<m_age<<"years old"<<endl;
}
};
class animalFactory{
public:
static animal* createCat(string name,string color)
{
Cat* p_cat=new Cat;
p_cat->m_color=color;
p_cat->m_name=name;
return p_cat;
}
public:
static animal* createdog(string name,string color,int age){
Dog* p_dog=new Dog;
p_dog->m_name=name;
p_dog->m_color=color;
p_dog->m_age=age;
return p_dog;
}
};
void friend_test(){
animal* cat=animalFactory::createCat("cat","black");
Cat* real_cat=dynamic_cast<Cat*>(cat);
real_cat->about();
animal* dog=animalFactory::createdog("dog","white",1);
Dog* real_dog=dynamic_cast<Dog*>(dog);
real_dog->about();
}
//运行结果如下:
//my name is cat,my color is black
//i am a dog,my name is dog,my color iswhite,i am 1years old
C++友元类,工厂模式和继承的融合案例
于 2023-12-13 20:09:30 首次发布