【发布时间】:2013-12-17 16:47:41
【问题描述】:
我开发了一个类,我们称之为 foo。在头文件中,我选择在 private: 部分中包含一个包含 foo 的所有私有成员的类。这样,如果我必须编辑 foo 的任何私有成员,我就不必重新编译每个使用 foo.h 的源文件。它是这样设置的:
#ifndef FOO_H
#define FOO_H
class fooData;
class foo
{
private:
fooPrivate *prv; // This class stores foo's private members
public:
foo(); // Default constructor
void bar();
}
#endif
我的 foo.cpp 类如下所示:
#include "foo.h"
class fooPrivate // Class which stores foo's private members
{
public:
void doMagic();
}
foo::foo()
{
prv = new fooPrivate; // Instantiate fooPrivate
prv->doMagic();
}
void foo::magic() // This is a public member function of foo
{
std::cout << "Magic!" << std::endl;
}
void fooPrivate::doMagic() // This is a function of private member fooPrivate
{
magic(); // I want to call a public member of foo here
}
你们中的大多数人已经知道我尝试从 doMagic() 调用 magic() 会导致的错误:
error: 'magic' was not declared in this scope
而且,更改对 foo::magic() 的调用会导致:
error: cannot call member function 'void foo::magic()' without onject
现在,我真的很想避免在 fooPrivate 类型的对象内实例化 foo 类型的对象,它本身是由 foo 类型的对象的实例化产生的......那么,有没有办法调用 public 来自 fooPrivate 的公共成员函数的成员函数 magic()?
【问题讨论】:
标签: c++