访问修饰符有三种:public、protected、private。
struct和class区别非常小,struct默认所有成员访问修饰符是public。
通过类中具有public访问修饰符的方法返回值,可以访问类中私有或者受保护成员。
1 #include<iostream>
2 using namespace std;
3
4 class A {
5 public:
6 int a=7;
7 int b;
8 int gets() {
9
10 }
11 };
12
13 struct node {//struct和class区别非常小,struct默认所有成员访问修饰符是public
14 private:
15 int a = 8;
16 int b;
17 public:
18 int getsA() {
19 int a = 9;
20 return this->a;
21 //return a;//直接写成员,相当于隐含了一个this
22 }
23 };
24
25 int main() {
26 A a;
27 cout << a.a << endl;
28 node m;
29 int a0 = m.getsA();//通过类中的具有public访问修饰符的方法,可以访问私有成员
30 cout << a0 << endl;
31 }
每一个成员函数里,会隐含的带一个this指针,this代表当前对象的地址,一个指向当前对象的地址。
没有this指针,如果传参时有相同名字的参数,一般会采用“就近原则”。
例如:
int getsA(int a) {
return a;//没有this指针,采取就近原则,返回值是形参a
}