类中的类可以从外部类调用 getter 方法吗?

Can a class inside a class call a getter method from the outer class?

本文关键字:getter 方法 调用 从外部      更新时间:2023-10-16

我在类中有一个类。

外部类执行一些处理以生成值数组。

我希望内部类能够访问外部类的数组。

有没有一种干净的方法来实现这一目标?

我正在考虑在外部类中有一个方法,该方法调用内部类中的方法向他发送数组的地址,并且内部类需要在其私有成员部分中保留一个指针,以便稍后通过从接收地址的方法赋值指向它。但这感觉有点笨拙。

在构造时,可以将外部类的引用传递给内部类的构造函数。 使用该引用,可以调用外部类的任何函数。


// The actual definition of the inner class.
class inner {
public:
inner(outer& o) : outer_(o) // Set the reference.
{
}
// The function using the data in outer.
void do_stuff() 
{
int x = outer_.get_data() + 5;
}
private:
// A reference to the outer class.
outer& outer_;
}
// The actual outer class.
class outer {
public:
outer() : inner_(*this) // Set the reference using the this object.
{
}
// This is the function you would like to call.
int get_data();
private:
inner inner_;
}

C++有一个嵌套类的概念。嵌套类,在另一个封闭类中声明。它是一个成员,并且具有与封闭类的任何其他成员相同的访问权限。但是封闭类的成员对嵌套类的成员没有特殊访问权限。可以参考此示例代码。希望这会有所帮助

class Outer {       
private:    
int arry[]; 
class inner { 
private:
int innerArr[];
void Fun(Outer *e) { 
innerArr = e->arry;   
}        
}; 
}; 
int main(){
Outer out;
Outer::inner in;
in.Fun(out);

}

好的,这是完整的。要点:

  • C++有嵌套类,但是这是处理范围和封装的 100% 编译时的事情,类实例是 100% 独立的。
  • 因此,如果您希望任一类以任何方式使用另一个类,则必须创建一个实例或接受一个实例。
  • (然后,给定一个外部实例,允许内部类访问其私有部分,这是唯一与正常作用域实际不同的部分)。

所以知道了这一点,这里有一个具体的例子。 → Outer 拥有 Inners 的向量。

→ Inner 需要使用其拥有的 Outer 实例
➥ 说 Outer 可能是某种列表,而 Inner 可能是某种项目

class Outer
{
public:  // can be private, in which case Inner won't be usable from outside
class Inner
{
Outer & m_outer;
public:
Inner(Outer & outer) : m_outer(outer) {}
void doOuterMagic() { m_outer.doMagic(); }
};
public:
void addInner() { m_inners.emplace_back(*this); }
private: // could be public, but I want to illustrate Inner access to private members
void doMagic() { std::cout <<"magic"; }
private:
std::vector<Inner> m_inners;
};

与任何类一样,如果外部类更具可读性,您也可以在外部类下面定义它。你会这样做:

class Outer
{
public:  // can be private, in which case Inner won't be usable from outside
class Inner;
public:
// ... unchanged ...
};
class Outer::Inner  // note the scoping here
{
// ... exactly what was in class Inner above
};

笔记:

  • 任何外部和内部关系都取决于你的设计,C++假设没有。
  • 如果 Outer 与 Inner 关系密切,那么让 Outer 创建 Inner 实例并将自身传递给它们是很常见的,就像我在这里addInner所做的那样。
  • 我做了m_outer参考,但这阻止了Inner满足*可分配的要求。如果需要类来满足这些要求,请改为将其设置为指针。