c++ - 在实现文件中添加成员函数

标签 c++ function class header declaration

作为家庭作业,我得到了一个骨架类,并被告知从源文件的头文件中实现功能。我不允许更改 header ,因为它不会被打开,只有实现文件。

但是,有一个函数我真的很想添加到类中( operator() 函数)。如何在不更改 header 的情况下将其声明为类的一部分?

我无法添加友元函数(需要更改 header 中的类定义)。我不能只在源代码的顶部实现它(行外定义不匹配......)。我不能在顶部重新声明类(类的重新定义)。

这可能吗?这样做可以避免将函数体复制到代码中的 4 个不同位置。

仅供引用,它是一个循环双向链表的访问器。 operator[] 用于访问列表元素元素,我需要一个返回列表元素指针的访问器。作为引用,运算符如下所示:

// CANT CHANGE THIS, ITS IN THE HEADER
Elem& operator[]( int i ) const;  

// THIS IS WHAT I WANT THOUGH
// ITS NOT IN THE HEADER, SO I CANT USE IT
CNode * CircleList::operator()( int i ) {

    CNode * n = this->header->next;

    if( i < 0 ) {

        while( i < 0 ) {
            n = ( n->prev == this->header ) ? ( n->prev->prev ) : ( n->prev );
            ++i;
        }

    } else if( i > 0 ) {

        while( i > 0 ) {
            n = ( n->next == this->header ) ? ( n->next->next ) : ( n->next );
            --i;
        }

    }

    return n;

}

(大部分)有问题的 header :

#include "point.h"
#include <stdlib.h>
#include <stdio.h>

typedef Point Elem;
class CNode{
private:
    Elem elem;
    CNode * next;
    CNode * prev;

    friend class CircleList;
};

class CircleList {
public:
    CircleList();
    ~CircleList();

    Elem& operator[](int i) const;
    void setElemAt (int i, const Elem newElem) const;
private:
    CNode * header;
    int _size;
};

最佳答案

However, there is a function I would really like to add to the class ( the operator() function ). How can I declare it to be part of the class without changing the header?

基本上,您不能。

你可以做的是:

  • 派生自该类并在其中添加您的operator()。当然,当其他代码必须使用具有值语义的原始类时,这是行不通的。
  • 将类包装为您自己类中的成员,并提供到原始类的用户定义转换。大多数情况下都不太好。
  • 拿出黑魔法,也称为预处理器,并将 header 包装在您自己的 header 中 with something like那:

    #define public \
      public: void operator()(void); public
    // original header content
    struct SomeClass {
      // stuff
      public: // We need this once, otherwise we're screwed
      // other stuff
    };
    // end original header content
    #undef public
    

    不过,这显然破坏了 ABI 与通过其原始 header 使用 SomeClass 的其他代码的兼容性。

Doing this will save me copying the function body to 4 different places in the code.

为什么你不能只写一个自由函数 call_it 而不是 object() 你在这 4 个中写 call_it(object)地方?

关于c++ - 在实现文件中添加成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39498218/

相关文章:

c++ - =delete 方法上的限定符

arrays - 什么时候返回数组或散列,什么时候只返回引用?

python - 无法使用从 python 中同一目录中的另一个文件访问的类

c++ - Wt布局头痛

c++ - 使用 gcc 构建共享库

c# - 如何从 ABBBBBGG GGGRRRRR 两个字节格式中读取颜色分量?

function - 哪些功能被认为是“可组合的”?

javascript - For 循环是否处理表达式内的函数直到循环结束?

python - 使用一个函数更新不同的类属性

c++ - 你会如何解决这个问题?老式学生/类(class)/学校代码。这是我的方法 :