如何将自己的方法添加到预先存在的类中,而不需要对预先存在的类的上下文进行任何更改。
例如:
A.hpp
class A
{
public :
void print1()
{
cout << "print1";
}
};
B.hpp
//add a helper function to class A
//for example:
A::print2()
{
cout << "print2";
}
main.cpp
#include "A.hpp"
#include "B.hpp"
main()
{
A a1;
a1.print2();
}
最佳答案
要在 C++ 中扩展类,请区分两种情况。
如果新函数可以用当前接口(interface)来表达,则使用非成员函数
// B.hpp
void print2(A const& a)
{
// pre-call extensions (logging, checking etc.)
a.print1();
// post-call extensions (logging, checking etc.)
}
如果新函数需要了解当前实现,请使用类继承
// B.hpp
// WARNING: here be dragons, read on before using this in production code
class B: public A
{
public:
void print2() const // compiler-generated signature: void print2(B const*)
{
// pre-call extensions (logging, checking etc.)
print1();
// post-call extensions (logging, checking etc.)
}
};
但是,从不打算作为基类的类派生可能会很危险。特别是,如果 A
没有 virtual
析构函数,如果您使用动态分配的指针,您可能会遇到麻烦 B
对象位于将被释放的位置,就好像它们是指向 A
的指针一样对象。
此外,因为A::print1()
未制作virtual
,你会遇到各种名称隐藏问题,这就是为什么你必须将扩展函数命名为 B::print2()
.
长话短说:知道您正在编写哪种类型的类(class)。如果您想基于类实现扩展行为,那么您最好使其适合作为基类(虚拟析构函数,可以重写的虚拟函数)。否则,将您的类(class)标记为 final
(新的 C++11 上下文关键字)。如果您尝试覆盖现有函数,这将生成编译器警告。
注意:在其他语言(特别是 D)中,可以让编译器自动查找非成员函数 print2(a)
当它看到语法 a.print2()
时。不幸的是,这种统一函数调用语法尚未出现在 C++ 的路线图上。
关于c++ - 如何向类添加方法(辅助函数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17638283/