是否可以在 C++ 中在不同的源文件中扩展一个类(添加一个方法),而无需编辑编写该类的原始源文件?
在 obj-c 中可以通过编写另一个 @interface AbcClass (ExtCategory) ... @end
当我尝试这样的事情时遇到编译时错误:
//Abc.h
class Abc { //This class is from a 3rd party library....
// ...I don't want to edit its source file.
void methodOne();
void methodTwo();
}
//Abc+Ext.h
class Abc { // ERROR: Redefinition of 'Abc'
void methodAdded();
}
我的目标是保留“Abc”名称并向其添加方法。我使用的第 3 方库中的特定类缺少一些方法,我想添加这些方法,但我未编辑源文件。
有没有办法做到这一点?我是编写 C++ 代码的新手。我熟悉它的一些语法,但了解不多。
最佳答案
没有。这种类扩展在 C++
中是不可能的。但是您可以从原始源文件继承一个类并在源文件中添加新功能。
//Abc.h
class Abc {
void methodOne();
void methodTwo();
};
//Abc+Ext.h
class AbcExt : public Abc {
void methodAdded();
};
然后你可以调用如下方法:
std::unique_ptr<AbcExt> obj = std::make_unique<AbcExt>();
obj->methodOne(); // by the virtue of base class
obj->methodAdded(); // by the virtue of derived class
关于c++ - 向其他文件中的现有 C++ 类添加方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18804402/