c++;对象模型的缺点。解决办法是什么? 我在C++学习阶段。在C++对象模型中阅读时,我理解了 不同的对象模型

c++;对象模型的缺点。解决办法是什么? 我在C++学习阶段。在C++对象模型中阅读时,我理解了 不同的对象模型,c++,C++,1) 简单对象模型 2) 表驱动对象模型 < P > 3)C++对象模型。< /P> 问题: 它的主要缺点是需要重新编译未经修改的代码,以使用已添加、删除或修改非静态类数据成员的类的对象 我理解上述说法。类定义中发生的任何更改 需要重新编译使用相同类的源代码 这意味着,在不重新编译的情况下也有一些原因可以实现相同的功能。怎么做?如果有人提供示例代码,那就太好了。我在Linux/Ubuntu中使用g++ 修改类时防止重新编译的典型习惯用法是PImpl < P>在其他语言/对象模型中可能有相同的实

1) 简单对象模型

2) 表驱动对象模型

< P > 3)C++对象模型。< /P> 问题:

它的主要缺点是需要重新编译未经修改的代码,以使用已添加、删除或修改非静态类数据成员的类的对象

我理解上述说法。类定义中发生的任何更改 需要重新编译使用相同类的源代码


这意味着,在不重新编译的情况下也有一些原因可以实现相同的功能。怎么做?如果有人提供示例代码,那就太好了。我在Linux/Ubuntu中使用g++

修改类时防止重新编译的典型习惯用法是PImpl


< P>在其他语言/对象模型中可能有相同的实现方式,但是在C++中没有。否则,这不是C++对象模型的缺点。

但是,可以通过(1)仅从库中导出接口(也称为纯抽象类)和(2)从不更改已发布的接口来减轻后果。如果必须添加新的API,请通过新接口导出它(即使它引用的是旧的/修改过的实现类)


我不确定代码示例会有多大帮助。这不是一种编码技术。如果您知道什么是纯抽象类,那么您已经准备好了。

请注意,在标头中公开实现细节可能有好处,但在细节更改时强制重新编译也有缺点;函数可以更容易地内联,这可以提高运行时性能。你需要决定在何时何地进行这种权衡才是值得的

通过引入额外级别的间接寻址,可以在源文件中隐藏所有私有实现细节。一种常见的方法是指向私有实现的指针(或“pimpl”)习惯用法,例如:

// Header file
class Thing {
public:
    Thing(...);
    ~Thing();

    // Public interface

private:
    struct Impl;
    std::unique_ptr<Impl> impl;
};

// Source file
struct Thing::Impl {
    // private details
};

Thing(...) : impl(new Impl(...)) {}
~Thing() {}

// Implementation of public interface
// Header file
class Thing {
public:
    virtual ~Thing() {}

    static std::unique_ptr<Thing> make(...);

    // Pure virtual public interface
};

// Source file
class ThingImpl : public Thing {
    // Implementation of public interface

    // Private implementation details
};

std::unique_ptr<Thing> Thing::make(...) {
    return std::unique_ptr<Thing>(new ThingImpl(...));
}
//头文件
阶级事务{
公众:
东西(…);
~Thing();
//公共接口
私人:
结构Impl;
std::唯一的\u ptr impl;
};
//源文件
结构物::Impl{
//私人细节
};
事物(…):impl(新impl(…){}
~Thing(){}
//公共接口的实现
另一种可能性是定义一个抽象接口,一个或多个工厂创建包含实现的具体实例,例如:

// Header file
class Thing {
public:
    Thing(...);
    ~Thing();

    // Public interface

private:
    struct Impl;
    std::unique_ptr<Impl> impl;
};

// Source file
struct Thing::Impl {
    // private details
};

Thing(...) : impl(new Impl(...)) {}
~Thing() {}

// Implementation of public interface
// Header file
class Thing {
public:
    virtual ~Thing() {}

    static std::unique_ptr<Thing> make(...);

    // Pure virtual public interface
};

// Source file
class ThingImpl : public Thing {
    // Implementation of public interface

    // Private implementation details
};

std::unique_ptr<Thing> Thing::make(...) {
    return std::unique_ptr<Thing>(new ThingImpl(...));
}
//头文件
阶级事务{
公众:
虚拟~Thing(){}
静态标准::唯一的ptr品牌(…);
//纯虚拟公共接口
};
//源文件
课堂内容mpl:公共事物{
//公共接口的实现
//私人实施详情
};
std::unique_ptr Thing::make(…){
return std::unique_ptr(newthingimpl(…);
}

这两种方法都将所有实现细节放在源文件中,因此当细节发生变化时,这是唯一需要重新编译的东西。但两者都引入了额外的指针间接和/或间接函数调用,这可能会影响运行时性能

你的问题不清楚,但你可能正在寻找答案。