local class and nested class
阿新 • • 發佈:2018-12-26
- 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;
}
};