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

标签 c++ scope polymorphism factory encapsulation

我有一个简单的 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/

相关文章:

c# - C++ .NET Wrapper : Attempted to read or write protected memory. 这通常表示其他内存已损坏

c++ - 使用 memcpy 重构字符串流的使用

python - 操作变量时出现 UnboundLocalError 产生不一致的行为

c++ - 什么时候在 C++ 中调用复制构造函数? - 函数返回

java - 这里的运行时类型对象是什么

c++ - 通过 C++ 在 qml 中交换 QString

c++ - 我需要通过我的函数传递什么样的参数。另外,如何让它根据用户需要循环多次?

java - 多态性的好处

types - 模块内的多态类型 (OCaml)

java - 在 Android 中使用 Native 的好处