【问题标题】:How to add method to a class (Helper function)?如何将方法添加到类(Helper 函数)?
【发布时间】:2013-07-14 09:51:47
【问题描述】:

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

例如:

   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++ c++11 non-member-functions


【解决方案1】:

要在 C++ 中扩展类,请区分两种情况。

如果新函数可以用当前接口表示,则使用非成员函数

// 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()

长话短说:知道您正在编写哪种课程。如果您想基于类实现扩展行为,那么您最好使其适合作为基类(虚拟析构函数,您可以覆盖的虚拟函数)。否则,将您的类标记为 final(新的 C++11 上下文关键字)。如果您尝试覆盖现有函数,这将生成编译器警告。

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

【讨论】:

  • 在delphi编译器中,当我们需要增加class的能力时(没有源码)我们可以为class写一个helper函数,这个helper函数类似于静态函数,公共属性有访问。
  • 这个答案是“不”这个词的一个很长的形式......但是+1。
猜你喜欢
  • 2012-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-02
  • 1970-01-01
  • 2015-12-06
  • 1970-01-01
  • 2016-11-15
相关资源
最近更新 更多