避免在类头文件(C ++)中声明私有函数

|| (在C ++中)我有一个类,其结构在头文件中声明。该头文件包含在许多源文件中,因此当我对其进行编辑时,我需要重新编译许多文件。 该类具有一组私有函数,这些私有函数仅在一个源文件中被调用。当前,它们在头文件的类结构中声明。当我添加这种类型的新功能或编辑参数时,因此会导致重新编译大量文件。我想在其他地方声明这些函数,以便仅重新定义并调用它们的文件(以节省时间)。但是,它们仍然需要能够访问内部类变量。 我该如何实现?     
已邀请:
使用pImpl习惯用法-您的可见类保留指向真实类的指针,并将调用转发给公共成员函数。 编辑:回应评论
// Foo.h:

class FooImpl; // Do *not* include FooImpl.h
class Foo {
public:
  Foo();
  ~Foo();
  //.. also need copy ctor and op=
  int bar();
private:
  FooImpl * Impl;
};

// FooImpl.h:

class FooImpl {
public:
  int bar() { return Bar; }
private:
  int Bar;
};

// Foo.cpp:

#include \"FooImpl.h\"

Foo::Foo() { Impl = new FooImpl(); }
Foo::~Foo() { delete Impl; }
int Foo::bar() { return Impl->bar(); }
将您的课程的实际实现保留在
FooImpl
中-
Foo
应该具有ѭ1members的公共成员的副本,并只需将其转发给这些成员即可。所有用户将仅包含\“ Foo.h \”-您可以更改
FooImpl
的所有私有详细信息,而
Foo
的用户不会看到任何更改。     
在主类声明之外无法声明类的成员函数。因此,如果您想在所讨论的类之外声明可以访问该类特定实例的成员变量的函数,那么我别无选择,只能将该实例传递给该函数。此外,如果您希望函数能够访问私有和受保护的变量,则需要将它们放在新类中,并使原始类成为该类的朋友。例如。 header.h:
class FooImpl;

class Foo {
public:
   int bar();
   friend class FooImpl;
private:
   int var;
}
impl.cpp:
#include \"header.h\"

class FooImpl {
public:
   int bar(Foo &);
}

int FooImpl::bar(Foo &foo) {
return foo.var;
}

int Foo::bar() {
return FooImpl::bar(*this);
}
    
您是否正在寻找Compiler Firewall,又称PIMPL?     
创建一个仅包含公共函数的抽象基类,并在标题中引用它。在其他地方创建您的真实类作为实现。只有需要创建您的类的源文件才需要查看实现类头。     

要回复问题请先登录注册