繁体   English   中英

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

[英]Avoiding declaring private functions in class header files (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应该有FooImpl公共成员的副本,并简单地转发对这些的调用。 所有用户将只包含“Foo.h” - 您可以更改FooImpl的所有私人详细信息,而不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);
}

你在寻找编译器防火墙 ,又名PIMPL?

创建一个抽象基类,它只包含公共函数,并在标题中引用它。 在其他地方创建您的真实类作为实现。 只有需要创建类的源文件才需要查看实现类头。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM