吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 155|回复: 0
上一主题 下一主题
收起左侧

[C&C++ 原创] 追踪类成员变量生命周期

[复制链接]
跳转到指定楼层
楼主
lrj2025kernel 发表于 2026-8-26 11:47 回帖奖励
本帖最后由 lrj2025kernel 于 2026-8-26 11:48 编辑

一、演示代码
[C++] 纯文本查看 复制代码
#include "stdio.h"
/* ===================================================================
 * [日期]:    2026年8月26日11时33分15秒
 * [功能]:    追踪类成员变量生命周期
 * =================================================================== */
class Trace {
public:
        Trace(const char* name) :m_name(name) {
                printf("%s\n", m_name);
        }
        ~Trace() {
                printf("%s\n", m_name);
        }
private:
        const char* m_name;
};
class CPerson {
public:
        CPerson():pid("CPerson::pid") {
                printf("%s\n", "CPerson::CPerson()");
        }
        virtual ~CPerson() {
                printf("%s\n", "CPerson::~CPerson()");
        }
private:
        Trace pid;
};
class Lesson {
public:
        Lesson():count("Lesson::count")
        {
                printf("%s\n", "Lesson::Lesson()");
        }
        ~Lesson() 
        {
                printf("%s\n", "Lesson::~Lesson()");
        }
private:
        Trace count;
};
class CStudent : public CPerson {
public:
        CStudent() :weight("CStudent::weight"), height("CStudent::height") 
        {
                printf("%s\n", "CStudent::CStudent()");
        }
        ~CStudent() 
        {
                printf("%s\n", "CStudent::~CStudent()");
        };
private:
        Trace    height;
        Trace    weight;
        Lesson   lesson;
};
int main(int argc, char* argv[]) {
        {
                CStudent one;
        }
        return 0;
}

二、运行结果

三、注意事项
1、即便CPerson类中的成员pid是私有成员,CStudent one;执行完毕后的子类CStudent内存模型中包含它,私有只是代码不能类外部访问(one->pid编译错误)并不代表子类内存模型中没有它,通过偏移仍可访问到

2、内存模型中成员排布顺序与类成员变量声明顺序一致,与初始化列表中的出现先后顺序无关

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - 52pojie.cn ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2026-8-26 19:02

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表