- local class
在一个函数里面声明的类从属于那个函数。比如说
void fun() {
class base {
private:
public:
};
}
local class 仅仅能够在函数内部声明对象
void fun() {
class base {
private:
int i;
public:
base() { cout << "1" << endl; }
void print() {
cout << "2" << endl;
}
};
base a;
a.print();
}
int main() {
base a;
return 0;
}
local class 里面的函数仅仅能够在函数内部定义
void fun(){
class base {
private:
int i;
public:
base() { cout << "1" << endl; }
void print() {
cout << "2" << endl;
}
};
base a;
a.print();
}
int main() {
fun();
return 0;
}
void fun() {
class base {
private:
int i;
public:
base() { cout << "1" << endl; }
void print();
};
void base::print() {
cout << "2" << endl;
}
base a;
a.print();
}
int main() {
fun();
return 0;
}
局部类不能定义静态变量,但可以定义静态函数
void fun() {
class base {
private:
int i;
public:
static int m;
void print() {
cout << "2" << endl;
}
};
base a;
a.print();
}
static int i2;
void fun() {
class base {
private:
int i;
public:
static void print() {
i2++;
cout << i2 << endl;
}
};
base a;
a.print();
}
int main() {
i2++;
fun();
return 0;
}
局部类仅仅能够访问本函数里或全局静态变量或者枚举量
void fun() {
static int i2;
enum tem
{
x=0,y=0
};
class base {
private:
int i;
public:
static void print() {
cout << "i2=" <<i2 << endl;
cout << "x=" << x << endl;
}
};
base a;
a.print();
}
int main() {
//i2++;
fun();
return 0;
}
void fun() {
int x;
class base {
private:
int i;
public:
void print() {
cout << "x=" << x << endl;
}
};
base a;
a.print();
}
局部变量可以访问全局变量,全局函数,还能够访问函数内部其他类
int x=2;
void fun() {
class base1 {
private:
public:int i=1;
void print() {
cout << "x=" << x << endl;
}
};
class base2 :public base1{
private:
int i;
public:
void print() {
cout << "base::i =" << base1::i << endl;
cout << "x=" << x << endl;
}
};
base2 a;
a.print();
}
int main() {
//i2++;
fun();
return 0;
}
- nested class
nested class是指在一个已经存在的类中定义的类,假设在A中定义了B,那么B就是nested class。
这其中,有如下规则:
B可以改变A成员值;
A不可以改变B成员值。
B可以改变A成员值
class base1 {
private:
int i;
class base2 {
private:
int i2;
public:
base2(int i1) :i2(i1) {}
void print(base1 *s) {
cout << "---" << s->i << endl;
}
};
public:
base1(int i1) :i(i1) {}
void print() {
cout << "---" << i << endl;
}
};
A不可以改变B成员值
class base3{
private:
int i;
class base2 {
private:
int i2;
public:
base2(int i1) :i2(i1) {}
};
public:
base3(int i1) :i(i1) {}
void print(base2 *s) {
cout << "---" << s->i2 << endl;
}
};