从私有结构数据成员访问类公共成员函数C++


我想

这可能是一个微不足道的语义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

如果没有办法进入公共成员功能,我会感到惊讶。任何关于如何解决这个问题的想法,不胜感激。谢谢!

你需要

一个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_;
};

最新更新