Eri*_*rik 14
使用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(); }
Run Code Online (Sandbox Code Playgroud)
保持班级的实际实施FooImpl- Foo应该拥有公共成员的副本,FooImpl并简单地转发对这些成员的调用.所有用户将仅包含"Foo.h" - 您可以更改所有私人详细信息,FooImpl而无需用户Foo查看任何更改.
无法在主类声明之外声明类的成员函数。因此,如果您想在所讨论的类之外声明可以访问该类特定实例的成员变量的函数,那么我认为别无选择,只能将该实例传递给该函数。此外,如果您希望函数能够访问私有变量和受保护变量,您需要将它们放在一个新类中,并使原始类成为它的朋友。例如
标题.h:
class FooImpl;
class Foo {
public:
int bar();
friend class FooImpl;
private:
int var;
}
Run Code Online (Sandbox Code Playgroud)
实现.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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20224 次 |
| 最近记录: |