c++ - 从私有(private)结构数据成员访问 C++ 类公共(public)成员函数

标签 c++ visual-studio-2010 access-specifier pimpl-idiom

我想这可能是一个微不足道的 C++ 语义问题,但我在 Windows (VS2010) 上遇到了这个问题。我有一个类如下:

class A {
public:
   some_type some_func();
private: 
   struct impl;
   boost::scoped_ptr<impl> p_impl;
}

我想从 struct impl 中定义的函数中访问函数 some_func ,如下所示:

struct A::impl {
   impl(..) {} //some constructor
   ...
   some_impl_type some_impl_func() {
     some_type x = some_func(); //-Need to access some_func() here like this
   }
};

VS 2010 上下文菜单显示错误,所以还没有费心构建:

Error: A non-static member reference must relative to a specific object

如果无法访问公共(public)成员函数,我会感到很惊讶。任何关于如何解决这个问题的想法都会受到赞赏。谢谢!

最佳答案

您需要一个 A 的实例。 A::impl 是与 A 不同的结构,因此隐式 this 不是正确的实例。在构造函数中传递一个:

struct A::impl {
   impl(A& parent) : parent_(parent) {} //some constructor
   ...
   some_impl_type some_impl_func() {
     some_type x = parent_.some_func(); //-Need to access some_func() here like this
   }

   A& parent_;
};

关于c++ - 从私有(private)结构数据成员访问 C++ 类公共(public)成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20821925/

相关文章:

c++ - 具有优化查找的容器,如 std::map 但非关联

c++ - "ClassName ClassName::FunctionName"在 C++ 中是什么意思?

c++ - 有什么理由更喜欢从 IDE 中运行应用程序而不是运行独立的可执行文件?

c# - visual studio 2010 c# winforms运行时编译

ruby-on-rails - 我们什么时候应该考虑使用 private 或 protected?

c++ - 我应该包装一个完全包含在 node.js 函数中的 C++ 对象吗?

visual-studio-2010 - Visual Studio 2010 启动时出现错误 "-832"不是属性 "width"的有效值

visual-studio-2010 - 我安装的 Visual Studio 2010 Express 不包含 “redist” 文件夹

java - 公共(public)与 protected 抽象类方法

java - 为什么 Java 的 "protected"的保护程度低于默认值?