0

我想知道是否有任何方法可以从其类外部查看(并且不访问也不修改)私有成员?

template <typename type_>
class OBJ1
{
  //methods
};

class OBJ2
{
  private:
    OBJ1<int> my_obj;
};

class OBJ3
{
  public:
    template <typename type_>
    void magic_method(OBJ1<type_> obj)
    {
      //with another intermediate class, call one of OBJ1's public methods
      //anotherClass::call(obj);
    }
};

显然这不起作用,因为 G++ 不知道my_obj. class OBJ3有没有办法让这段代码编译?像前向声明什么的?同样,其他类只需要知道“OBJ1 声明的对象”存在。

谢谢 !

4

3 回答 3

0

任何一个

void magic_method(OBJ1<int>& my_obj)
{
  //with another intermediate class, call one of OBJ1's public methods
}

或者,如果您想OBJ1通用:

template<typename T>
void magic_method(OBJ1<T>& my_obj)
{
  //with another intermediate class, call one of OBJ1's public methods
}
于 2012-10-03T09:55:58.787 回答
0

我不确定你到底想要什么......但如果我理解正确你想从 OBJ3 中访问 OBJ2 私人部分。

template <typename type_>
class OBJ1
{
  //methods
};

template <typename type_>
class OBJ2
{
  private:
    OBJ1<type_> my_obj;
    friend class OBJ3;
};

class OBJ3
{
  public:
    template <typename type_>
    void magic_method(OBJ2<type_> obj)
    {
      std::cout << obj.my_obj;
      //with another intermediate class, call one of OBJ1's public methods
      //anotherClass::call(obj);
    }
}
于 2012-10-03T10:26:36.163 回答
0
// call one of OBJ1's *public* methods

您可以轻松完成这项工作,如下所示。实际问题是什么,OBJ2与任何事情有什么关系?显示您担心的私人访问错误的发布代码。

#include <iostream>
#include <typeinfo>

template <typename type_>
class OBJ1
{
  public:
  void print_type_name() {
    std::cout << typeid(type_).name() << "\n";
  }
};

/*
class OBJ2
{
  private:
    OBJ1<int> my_obj;
};
*/

class anotherClass {
  public:
    template <typename type_>
    static void call(OBJ1<type_> obj) {
        obj.print_type_name();
    }
};

class OBJ3
{
  public:
    template <typename type_>
    void magic_method(OBJ1<type_> obj)
    {
      //with another intermediate class, call one of OBJ1's public methods
      anotherClass::call(obj);
    }
};

int main() {
    OBJ3 obj3;
    OBJ1<int> obj1;
    OBJ1<double> objd;
    obj3.magic_method(obj1);
    obj3.magic_method(objd);
}
于 2012-10-03T12:24:20.623 回答