[英]How to call outer classes functions with the same name as the calling inner class function
标题说明了一切。 假设我有这个:
struct Outer
{
struct Inner
{
void a(int i) {
Outer::a(i); // Error: Illegal of non-static member function
}
};
void a(int i) {}
};
Inner::a
声明会怎样?
不可能。 外部和内部 class 之间甚至没有固定关系(如聚合),您可以创建没有外部实例的内部实例,反之亦然。
顺便说一句:这两个成员函数都称为a
的事实在这里完全无关紧要。
如何调用与调用内部class function同名的外部类函数?
在尝试直接访问成员函数之前,您必须需要创建 class 的实例。
因此,有两种方法可以做到这一点:
使用static
声明 function 签名。
创建Outer
的实例并使用点运算符访问成员 function。
示例 1:
struct Outer {
struct Inner {
void a(int i) {
Outer::a(i); // direct member function access
}
};
static void a(int i) { // declared as static
std::cout << i << std::endl;
}
};
int main(void) {
Outer::Inner in;
in.a(10); // Inner class calls the member of Outer class's a(int)
return 0;
}
示例 2:
struct Outer {
struct Inner {
void a(int i) {
Outer x; // instance to the class Outer
x.a(i); // accessing the member function
}
};
void a(int i) { // outer class definition
std::cout << i << std::endl;
}
};
int main(void) {
Outer::Inner in; // creating an instance of Inner class
in.a(10); // accessing the Inner member function (which accesses
// Outer class member function)
return 0;
}
如果您来自 java,则 C++ 中的声明
class Outer {
class Inner {
};
};
在 java 中表示:
class A {
static class B { // <- static class
};
};
c++ 中的所有内部类都与 java 中的static
内部类“等效”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.