美文网首页
monolake 的GeekBand C++开发学习笔记(四)

monolake 的GeekBand C++开发学习笔记(四)

作者: monolake | 来源:发表于2016-06-06 09:06 被阅读0次

前记:进入面向对象编程(下)的课程,在(上)概念建立完成后,进入了实用知识填充阶段:本周主要讲类中转换函数,显式调用explicit(禁隐式调用),智能指针,仿函数,类模版,函数模板,模板参数的模版类,模板特化,模板偏特化,名称空间namespace。具体内容课程有讲,我不具体罗列。以下我记录的一些小tips供大家分享。

this指针

基类的this指针,派生类的this指针。
在基类中写调用一个函数包含:cout<<sizeof(this),在派生类中写一个函数包含:cout<<sizeof(this).用派生类对象同时调用这两个函数时,发现得出的结果不一致,基类的sizeof(this)为对象基类部分大小,派生类sizeof(this)为整个对象的大小。
如例:

#include<iostream>
using namespace std;
class Base
{
    int no;
    double weight;
    char key;
public:
    void print() { cout << sizeof(*this)<<endl; };
};

class Dired : public Base
{
    int size;
    char type;
public:
    void print() { cout << sizeof(*this) << endl; };
};
int main()
{
    Base A;
    Dired B;
    A.print();
    B.print();
    cin.get();
}

结果:

this

可以看出不一样。看来this指针也是类中所属的属性,基类的this和派生类this分别指的是自己独有的内容。

相关文章

网友评论

      本文标题:monolake 的GeekBand C++开发学习笔记(四)

      本文链接:https://www.haomeiwen.com/subject/iuirdttx.html