Skip to content

Commit 7a2634c

Browse files
添加成员函数空指针调用
1 parent d35c315 commit 7a2634c

File tree

2 files changed

+61
-6
lines changed

2 files changed

+61
-6
lines changed

C++/C++常见知识点.adoc

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,45 @@ private:
411411
};
412412
----
413413

414+
=== C++对象模型
415+
416+
417+
418+
419+
==== 为什么nullptr指针能调用成员函数
420+
421+
C++中非虚成员函数和普通函数都是存储在全局代码区的,区别就是C++总成员函数调用会默认生成一个this指针作为第一个参数传入到函数中,如:
422+
423+
[source, cpp]
424+
----
425+
class MyClass {
426+
public:
427+
MyClass(int value) : data(value) {}
428+
429+
void printData() const {
430+
//std::cout << data << std::endl;
431+
}
432+
433+
private:
434+
int data;
435+
};
436+
----
437+
438+
调用堆栈如下,编译器会自动将函数首个参数设置为this指针。
439+
440+
[source, cpp]
441+
----
442+
#0 MyClass::printData (this=0x0) at E:\work\note_book\src\main.cpp:34
443+
#1 0x0000000000401571 in main () at E:\work\note_book\src\main.cpp:44
444+
#2 0x00000000004013c7 in __tmainCRTStartup ()
445+
----
446+
447+
因此,非虚函数能从全局代码去找到,this指针虽然为nullptr依然能够当成正常的参数传递,只要不再函数内部使用this指针就行。
448+
449+
但是虚函数不能使用nullptr指针调用,因为虚函数是动态绑定的,需要调用对象里面的虚函数表查找对应的函数,因此需要调用this指针。
450+
451+
452+
414453

415454
=== 重载和重写的区别
416455

src/main.cpp

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,20 +25,36 @@ using namespace std;
2525

2626
const char * const SubStatusStr[] = {"init", "subscribe", "subscribed", "deleteting", "firstSub"};
2727

28+
class MyClass {
29+
public:
30+
MyClass(int value) : data(value) {}
2831

32+
virtual void printData() const {
33+
//std::cout << data << std::endl;
34+
}
2935

30-
int main(int argc, char* argv[]) {
36+
private:
37+
int data;
38+
};
3139

40+
class MyClass1 {
41+
public:
42+
MyClass(int value) : data(value) {}
3243

44+
virtual void printData() const {
45+
//std::cout << data << std::endl;
46+
}
3347

34-
std::atomic<uint32_t> iCount;
48+
private:
49+
int data;
50+
};
3551

36-
iCount.store(108);
3752

38-
iCount.store(iCount.load() % 100);
39-
40-
std:cout << iCount << std::endl;
53+
int main() {
54+
MyClass *lpObj = new MyClass(1);
4155

56+
// 调用成员函数
57+
lpObj->printData(); // 静态绑定调用
4258

4359
return 0;
4460
}

0 commit comments

Comments
 (0)