gpt4 book ai didi

c++ - 如何向类添加方法(Helper 函数)?

转载 作者:行者123 更新时间:2023-11-30 01:58:17 27 4
gpt4 key购买 nike

如何在不更改现有类的上下文的情况下将我自己的方法添加到预先存在的类中。

例如:

   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)标记为 final (新的 C++11 上下文关键字)。如果您尝试覆盖现有函数,这将生成编译器警告。

注意:在其他语言(尤其是 D)中,可以让编译器自动查找非成员函数 print2(a)当它看到语法 a.print2() 时.不幸的是,这种统一的函数调用语法还没有出现在 C++ 的路线图上。

关于c++ - 如何向类添加方法(Helper 函数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17638283/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com