/**
* 嵌套类与外围类间的成员访问
* 1. 外围类不能访问嵌套类的非静态数据成员, 反之亦然;
* 2. 外围类可以访问嵌套类的静态成员,但必须加上名字限定,嵌套类可以访问外围类的静态成员
* 3. 在外围类的成员函数中,可以直接调用嵌套类的静态成员函数,但调用非静态成员函数必须借助嵌套类对象来调用
* 4. 在嵌套类的成员函数中,可以直接调用外围类的静态成员函数,但不能调用非静态函数,即使加enclose::也不行
*
*/
#include <iostream>
using namespace std;
int x,y; // globals
class enclose { // enclosing class
int x; // note: private members
static int s;
public:
int z;
struct inner { // nested class
int m;
static int n;
inner() {
std::cout << "this is inner's constructor..." << std::endl;
}
void f(int i) {
std::cout << "this is inner's function f..." << std::endl;
// x = i; // Error: can't write to non-static enclose::x without instance
// z = i; //Error
// std::cout << z << std::endl; //Error :invalid use of non-static data member ‘enclose::z’
int a = sizeof x; // Error until C++11,
// OK in C++11: operand of sizeof is unevaluated,
// this use of the non-static enclose::x is allowed.
s = i; // OK: can assign to the static enclose::s,嵌套类可以访问外围类的静态成员
::x = i; // OK: can assign to global x
y = i; // OK: can assign to global y
}
void g(enclose* p, int i) {
p->x = i; // OK: assign to enclose::x
}
void h() {
std::cout << "this is inner's function h..." << std::endl;
}
static void i() {
std::cout << "this is inner's static function i..." << std::endl;
}
void j() {
std::cout << "this is inner's function j..." << std::endl;
enclose_d();
// enclose_c();//嵌套类可以调用外围类的静态成员函数,但不能调用非静态函数,即使加enclose::也不行
}
};
void enclose_b() {
inner();
}
void enclose_a() {
inner in;
in.h();//非静态函数必须借助嵌套类的对象来调用
}
void enclose_c() {
inner::i();//嵌套类的静态函数可以直接调用
std::cout << inner::n << std::endl;//外围类可以访问嵌套类的静态成员,但必须加上名字限定
}
static void enclose_d() {
std::cout << "this is enclose's static function enclose_d..." << std::endl;
}
// void enclose_e() {
// std::cout << inner::m << std::endl;// Error: m is not declare in this scope 外围类不能访问嵌套类的非静态数据成员,即使加了名字限定也不行
// }
};
int main(int argc, char const *argv[]) {
/* code */
return 0;
}
C++ 嵌套类与外围类间的成员访问
最新推荐文章于 2025-05-19 17:53:06 发布