gpt4 book ai didi

c++ - 从工厂创建的实例访问派生类的成员

转载 作者:行者123 更新时间:2023-11-30 02:35:56 24 4
gpt4 key购买 nike

我有一个简单的 Shape 工厂示例,我可以在其中创建 CircleSquare

我向 Circle 类添加了一个额外的“contents”属性,它不是 Square 派生类或 的一部分>Shape 基类。

问题是,当我使用工厂创建 Circle 类的实例时,我无法修改所创建对象的 contents

#include <iostream>

using namespace std;

// Shape base clas
class Shape {
public:

// Shape constructor;
Shape() {
id_ = total_++;
}

// Virtual draw method
virtual void draw() = 0;

protected:

int id_;
static int total_;
};
int Shape::total_ = 0;

// Circle derived class
class Circle : public Shape {
public:
void draw() {
contents = 0;
cout << "circle " << id_ << ": draw, contents: " << contents << endl;
}

// Attribute to attempt to access
int contents;
};

// Square derived class
class Square : public Shape {
public:
void draw() {
cout << "square " << id_ << ": draw" << endl;
}
};

// Factory class
class Factory {
public:
Shape* createCurvedInstance() {
return new Circle;
}
Shape* createStraightInstance() {
return new Square;
}
};

// Main
int main()
{
Factory* factory = new Factory;
Shape* thing = factory->createCurvedInstance();

// Draw method works fine (as it should)
thing->draw();

// Fails: "expression must have class type"
thing.contents = 4;

system("pause");

return 0;
}

当我使用工厂创建派生类的实例时,如何访问派生类的属性?

最佳答案

没有办法,除非你施法,而你不得施法。多态背后的整个想法是它们通过不可变接口(interface)使自己可用的实例。他们强调 IS-A 复制关系,其中 Circle 是所有意图和目的的 Shape,除了实现细节,没有人感兴趣。如果你向你的 Circle 公开添加“内容”,它就不再是 Shape,所以它不应通过工厂构建。

关于c++ - 从工厂创建的实例访问派生类的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33290339/

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