标题说明了一切。假设我有这个:
struct Outer
{
struct Inner
{
void a(int i) {
Outer::a(i); // Error: Illegal of non-static member function
}
};
void a(int i) {}
};
Inner::a
声明会如何?
答案 0 :(得分:2)
没有办法。外部类和内部类之间甚至没有固定的关系(例如聚合),您可以创建内部实例而没有外部实例,反之亦然。
顺便说一句:这两个成员函数都被称为a
的事实在这里是完全无关的。
答案 1 :(得分:0)
如何调用与调用内部类函数同名的外部类函数?
您必须先创建该类的实例,然后才能尝试直接访问成员函数。
因此,有两种方法可以做到这一点:
使用static
声明函数签名。
创建Outer
的实例,并使用点运算符访问成员函数。
示例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;
}
答案 2 :(得分:-1)
如果您来自Java,那么C ++中的声明
class Outer {
class Inner {
};
};
在Java中是指
class A {
static class B { // <- static class
};
};
c ++中的所有内部类都与Java中的static
内部类“等效”