头衔说明了一切。 假设我有这个:
struct Outer
{
struct Inner
{
void a(int i) {
Outer::a(i); // Error: Illegal of non-static member function
}
};
void a(int i) {}
};
inner::a
声明是怎样的?
没办法。 在外部类和内部类之间甚至没有固定的关系(比如聚合),您可以创建没有外部实例的内部实例,反之亦然。
顺便说一句:这两个memberfunctions都被称为a
这一事实在这里是完全不相关的。
如何调用与调用内类函数同名的外类函数?
在尝试直接访问成员函数之前,必须先创建类的实例。
因此,有两种方法可以做到这一点:
>
使用statice
声明函数签名。
创建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;
}
如果你来自Java,C++中的声明
class Outer {
class Inner {
};
};
在Java的含义:
class A {
static class B { // <- static class
};
};
C++中的所有内部类都与Java中的静态
内部类相当