向其他文件中的现有C ++类添加一个方法 [英] Add a method to existing C++ class in other file

查看:85
本文介绍了向其他文件中的现有C ++类添加一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有可能在C ++中扩展一个类(添加一个方法)在不同的源文件,而无需编辑类的原始源文件?

Is it possible in C++ to extend a class(add a method) in different source file without editing the original source file where the class is written?

在obj-c中,可以写另一个 @interface AbcClass(ExtCategory)... @end

In obj-c it is possible by writing another @interface AbcClass (ExtCategory) ... @end

我尝试这些时遇到编译时错误:

I got compile-time error when I tried these:

//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'名称和添加方法。在我使用的第三方库中的一个特定类缺少一些方法,我想添加这些方法,但我保持源文件未编辑。

How can I add a method without creating a derived class? My target is to retain the 'Abc' name and add methods to it. A specific class in a 3rd party library that I used lacks some methods and I want to add those methods but I am keeping the source file unedited.

有办法做这个?我是写C ++代码的新手。我熟悉它的一些语法,但不知道太多。

Is there a way to do this? I am new in writing C++ codes. I am familiar with some of its syntax but don't know much.

推荐答案

否。这种类扩展在 C ++ 中是不可能的。你可以继承你的类并添加新的功能。

No. This kind of class extension is not possible in C++. You can inherit your class and add new functions in there though.

//Abc.h
class Abc {
    void methodOne();
    void methodTwo();
}


//Abc+Ext.h
class AbcExt : public Abc {       
    void methodAdded();
}

然后,您可以按如下所示调用方法:

You can then call methods as following:

AbcExt *obj = std::make_unique<AbcExt>();
obj->methodOne(); // by the virtue of base class
obj->methodAdded(); // by the virtue of derived class

这篇关于向其他文件中的现有C ++类添加一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆