类中的类可以从外部类调用 getter 方法吗?
Can a class inside a class call a getter method from the outer class?
我在类中有一个类。
外部类执行一些处理以生成值数组。
我希望内部类能够访问外部类的数组。
有没有一种干净的方法来实现这一目标?
我正在考虑在外部类中有一个方法,该方法调用内部类中的方法向他发送数组的地址,并且内部类需要在其私有成员部分中保留一个指针,以便稍后通过从接收地址的方法赋值指向它。但这感觉有点笨拙。
在构造时,可以将外部类的引用传递给内部类的构造函数。 使用该引用,可以调用外部类的任何函数。
// 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
满足*可分配的要求。如果需要类来满足这些要求,请改为将其设置为指针。
相关文章:
- 私有变量无法正常工作的C++getter方法(只有Java经验)
- 不一定获得成员价值的 getter 方法?
- 派生类继承的 getter,找不到返回正确值的方法
- 类中的类可以从外部类调用 getter 方法吗?
- C++ getter 方法调用构造函数
- 枚举器 C++ 的 setter 和 getter 方法
- 访问属性或使用 getter 方法
- getter 方法的推荐签名是什么?
- 如何编写getter方法,使其返回右值
- 调用简单getter方法后出错:basic_string::_S_create
- 从getter方法返回常量和非常量值
- 命名重载的getter方法:const和nonconst
- 除非指定关键字,否则无法调用 getter 方法 "this"
- C++Getter方法打印奇怪的数字
- Valgrind:getter方法中包含rdlock的线程加载冲突
- 在调用右值对象的getter方法时获取右值
- 指向对象的指针的私有矢量.如何使用getter方法访问这些对象
- 通过在getter方法上应用begin()获得的迭代器不允许访问指向列表的第一个元素
- getter方法中的Const引用
- 尝试返回同一类中的私有变量时C++ "Getter"方法抛出访问冲突