【问题标题】:How to define a private member function only in cpp如何仅在 cpp 中定义私有成员函数
【发布时间】:2021-12-28 16:30:18
【问题描述】:

所以考虑我有一个带有私有成员变量和私有函数的类,我不想在头文件中定义它,因为我想对用户“隐藏”它。

我怎样才能做到这一点?如果没有在标头中声明函数,我将无法访问私有变量。

那么有效的是这样的:

// header file
class Testclass { 
  public:
    // ...
  private:
    const int m_i;
    void func() const;
}


// cpp file
#include "TestClass.h"

Testclass::func() const {
  int j = m_i; //access to a private member variable
}

// ...

但我想要这样的东西:

// header file
class Testclass{ 
  public:
    //...
  private:
    const int m_i;
}

// cpp file
#include "TestClass.h"

Testclass::func() const {
  int j = m_i; //access to a private member variable
}

// ...

我有哪些可能性?我读过一些关于 PIMPL 成语的东西,但我不确定这是否是我想要的,因为它看起来有点麻烦。

【问题讨论】:

  • 成员函数,包括私有函数,是类定义的一部分。如果您不希望看到 Testclass 定义的代码甚至看到 Testclass::func 的签名,则需要额外的间接层,例如 Pimpl 习惯用法。
  • PIMPL 实现您想要的。如果对你的口味太繁琐,那就把私有成员放在头部。
  • class Testclass { friend class HelperTestclass; }; 那么您可以使用 HelperTest 类作为悬挂所有非公共消费物品的地方。
  • 谢谢大家!我以为我会错过一些基本的东西。如果必须的话,似乎 Pimpl 和朋友是最好的选择。

标签: c++ static standards private


【解决方案1】:

通常通过PIMPL(指向实现的指针)习语来实现这一点。在您的头文件中,您有:

class MainClass
{
public:
    void public_function();
private:
    class Impl;
    Impl* impl;
};

注意头文件不包含Impl类的定义,只包含它的声明。

然后您在 cpp 文件中定义该类并将调用从您的公共接口转发到 impl 类的函数:

class MainClass::Impl
{
    void actualfunc()
    {
        //do useful stuff here
    }

};

void MainClass::public_function()
{
    return impl->actualfunc();
}

除了对类用户隐藏不需要的成员之外,PIMPL 习惯用法还提供了额外的好处,即如果不对类的接口进行任何更改,则无需重新编译类的用户。

【讨论】:

  • 使用唯一指针。
【解决方案2】:

您可以在 cpp 文件中包含非成员帮助函数,类成员可以使用这些函数。但是,他们必须将私有变量作为参数传递。

// header file
class Testclass{ 
  public:
    //...
  private:
    const int m_i;
}

// cpp file
#include "TestClass.h"

void func(int m_i) {
  int j = m_i; //private member variable supplied by caller
}

// ...

【讨论】:

    猜你喜欢
    • 2018-01-07
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    • 2015-04-01
    相关资源
    最近更新 更多