C++ - Class 函数可以在头文件之外声明吗?

C++ - Can Class Functions be Declared Outside of Header?

我是 C++ 的新手,我正在尝试编写一个 class,其目的是在使用输入实例化 class 时解决一个数学问题。我已经将这些计算分解为几个子函数,因此 header/source 代码看起来像这样:

mySolver.h

#ifndef __mySolver_h__

class mySolver
{
private:
    double mInput, mOutput; //member variables
    double intermediateCalculation1(double input);
    double intermediateCalculation2(double intermediateValue1);
public:
    mySolver(double input);
};

#endif

mySolver.cpp

#include "mySolver.h"

mySolver::mySolver(double input)
{
    mInput = input;

    double intermediateValue1 = intermediateCalculation1(mInput);
    double mOutput = intermediateCalculation2(intermediateValue1);

    cout << "Output is: " << mOutput << endl;
 }
double mySolver::intermediateCalculation1(double input)
{
    //do stuff
}

double mySolver::intermediateCaluclation2(double intermediateValue1)
{
    //do stuff while accessing value of member variable mInput
}

这有效但是我必须在头文件中列出方法intermediateCalculation1/2,尽管它们纯粹是实现细节。因此,如果我想更改计算执行方式的一些细节(例如,将事情分成 3 个中间计算而不是 2 个),我将不得不更改头文件并重新编译包含 [=38 的每个文件=] 这似乎违背了将接口与实现分离的目的。

我的问题是:

1) 有没有一种简单的方法可以做到这一点而不必在头文件中包含中间函数?

2) 有没有一种简单的方法可以做到这一点,而不必在头文件中包含中间函数,它仍然允许我访问中间函数中的成员变量

我发现了一些对 pImpl technique 的引用,这可能是一个解决方案,但就我的目的而言,这似乎不必要地复杂。

编辑:关于为什么这在 class 中,为了清楚起见,我简化了我的示例,但在我的实际代码中,我有多个输出,其中一些是我只想访问的中间结果有时(即用于错误检查),因此我选择 class 结构。

您可以通过在 .cpp 文件中使用它们之前定义函数来实现。不需要在头文件中定义它们,因为不需要使它们成为成员函数。这些只是免费功能。

此外,您可能希望将它们放在匿名命名空间中,这样它们只对现有文件可见。

1) Is there a simple way to do this without having to include the intermediate functions in the header file?

是的。除了 之外,如果将它们放入匿名(未命名)命名空间中,您将真正隐藏这些实现细节,以防止翻译单元之外的任何访问。它还有助于在名称冲突的情况下不混淆链接器:

namespace { // <<<< unnamed namespace
    double intermediateCalculation1(double input) {
        //do stuff
    }

    double intermediateCaluclation2(double intermediateValue1, double input) {
        // the member variable mInput should be passed as parameter
    }
}

mySolver::mySolver(double input) {
    mInput = input;

    double intermediateValue1 = intermediateCalculation1(mInput);
    mOutput = intermediateCalculation2(intermediateValue1,mInput);

    cout << "Output is: " << mOutput << endl;
}

2) Is there a simple way to do this without having to include the intermediate functions in the header file that still lets me access member variables in the intermediate functions?

不一定,这些需要 friended 才能这样做,这要求它们出现在 class 声明中。

您仍然可以像您的代码示例现在那样选择并将必要的参数传递给它们,或者使用您提到的 pimpl 习惯用法。由于pimpl只需要前向声明,我相信你也可以在匿名命名空间中进行完整的声明和定义。