【问题标题】:How to access private class variable from non-member function [duplicate]如何从非成员函数访问私有类变量[重复]
【发布时间】:2021-06-27 10:34:11
【问题描述】:

从下面截取的代码中,需要访问 A::B 类的成员函数。由于 B 类是私有的,因此无法从非成员函数为其创建对象。请帮助我解决这个问题,而无需将Class B 公开

以下代码供参考

啊.h

#include <iostream>

class A
{
public:
  A();
  void Func();
private:
  class B;
  B *b;
};

A.cpp

#include "A.h"
#include "AB.h"

A::A()
{
    b = new B(this);
}
void A::Func()
{
    b->Func();
}

AB.h

#include "A.h"

class A::B
{
public:
  B(A* a);
  void Func();
private:
  A* ptr;

};

AB.cpp

#include "AB.h"

A::B::B(A* a):ptr(a)
{

}

void A::B::Func()
{
    std::cout<<"Do nothing ";
}
static void call_sample()
{
    A::B* tmp;
    //access member function of class A::B
}

以下错误供参考:

In file included from AB.cpp:2:0:
AB.h: In function ‘void call_sample()’:
AB.h:3:10: error: ‘class A::B’ is private
 class A::B
          ^
AB.cpp:15:4: error: within this context
 A::B* tmp;

【问题讨论】:

  • 你为什么不上课Bpublic
  • 看起来call_sampleA::B 的实现细节,所以将它作为A::B 的私有静态成员是有意义的。
  • 您打算访问A::B 的哪个实例?单独上课对你没有好处。 (这看起来像 XY problem。)
  • 很抱歉,由于其他原因,B 类无法公开,因此缺少必要条件

标签: c++ class private


【解决方案1】:

B 是来自A 的嵌套类,它是私有的,因此,作为定义,它不能从外部访问。如果你需要使用B,你可以在A的公共部分取消B,然后你可以使用A::B*类型。

【讨论】:

  • 很抱歉,由于其他原因,B 类无法公开,因此缺少必要条件
  • 如果你已经将B作为私有插入,然后你需要将它作为“公共”使用,那么你的程序中有错误的逻辑
猜你喜欢
  • 1970-01-01
  • 2020-01-27
  • 1970-01-01
  • 2013-02-01
  • 2023-03-23
  • 2021-02-04
  • 1970-01-01
  • 2015-04-20
  • 2014-06-13
相关资源
最近更新 更多