总结
类的非静态成员函数的第一个参数默认都有一个指向对象的this指针,该this指针指向非静态成员函数所作用的对象。 静态成员为所有对象共享。
一、空指针访问类的非静态成员函数
1.该成员函数不访问成员变量
#include<iostream>
using namespace std;
class testThis{
public:
int i = 9;
void func(){
cout<<"call member function"<<endl;
}
void iFunc(){
cout<<"i:"<<i<<endl;
}
};
int main(){
testThis* a = NULL;
a->func();
testThis* b = nullptr;
b->func();
cout<<"--------------"<<endl;
testThis* d = new testThis();
d->iFunc();
return 0;
}
输出结果:
2.该成员函数访问成员变量
#include<iostream>
using namespace std;
class testThis{
public:
int i = 9;
void func(){
cout<<"call member function"<<endl;
}
void iFunc(){
cout<<"i:"<<i<<endl;
}
};
int main(){
testThis* a = NULL;
a->func();
testThis* b = nullptr;
b->func();
testThis* c = NULL;
c->iFunc();
cout<<"--------------"<<endl;
testThis* d = new testThis();
d->iFunc();
return 0;
}
输出结果:
二、空指针访问类的静态成员函数
#include<iostream>
using namespace std;
class testThis{
public:
int i = 9;
void func(){
cout<<"call member function"<<endl;
}
void iFunc(){
cout<<"i:"<<i<<endl;
}
void static staticFunc(){
cout<<"static member function"<<endl;
}
static void staticFuncTwo(){
cout<<"staticTwo member function: "<<s<<endl;
}
private:
static int s;
};
int testThis::s = 10;
int main(){
testThis* e = NULL;
e->staticFunc();
e->staticFuncTwo();
return 0;
}
输出结果:
谢谢观看,祝顺利。
小林coding: C++ this指针的理解和作用https://blog.csdn.net/qq_34827674/article/details/103303060
|