C++ 继承同一个的基类的所有派生类使用同一个全局变量的三种方式

定义全局变量类型

#ifndef D_HPP
#define D_HPP
#include <stdio.h>
class D
{
public:
	D() {printf("DDDDDDDD \n");}
	~D() {};

};

#endif // D_HPP

基类外声明和定义static变量

基类

A.hpp

#include "D.hpp"
static D d;

class A
{
public:
	A() {}
	~A() {}
	D* getD() { return &d;}
};
#endif // A_HPP

派生类B

B.hpp

#ifndef B_HPP
#define B_HPP

#include "A.h"

class B : public A
{
public:
	B():A() {printf("BBBBBBBBBBBB + %p\n", getD());}
	~B() {}
	

};

#endif // B_HPP

派生类C

C.hpp

#ifndef C_HPP
#define C_HPP

#include "A.h"

class C : public A
{
public:
	C():A() {printf("BBBBBBBBBBBB + %p\n", getD());}
	~B() {}
	

};

#endif // C_HPP

执行结果

#include <stdio.h>
#include "B.h"
#include "C.h"

int main(int argc, char **argv)
{
	B b;
	C c;
	return 0;
}

在这里插入图片描述

注意事项:

我们开发习惯将函数实现放在cpp文件中,如下
A.h

#include "D.hpp"
static D d;

class A
{	
public:
	A();
	~A();
	D* getD();
};

#endif // A_HPP

A.cpp

#include "A.h"
A::A()
{
}

A::~A()
{
}

D* A::getD() { return &d; }

B,C派生类写法类似,执行结果为:
在这里插入图片描述
可以看到执行了多次D类的构造函数,想要解决这个问题可以使用第二种方式extern

基类头文件定义extern变量,cpp文件初始化

基类

#include "D.hpp"
extern D* d;

class A
{
	
public:
	A();
	~A();
	D* getD();
};

#endif // A_HPP
#include "A.h"
D* d = new D();
A::A()
{
}

A::~A()
{
}

D* A::getD() { return d; }

执行结果

在这里插入图片描述

基类内声明,基类外定义static变量

基类

#ifndef A_H
#define A_H

#include "D.hpp"

class A
{
	
public:
	static D d;
	A();
	~A();
	D* getD();
};

#endif // A_HPP

#include "A.h"
D A::d;
A::A()
{
}

A::~A()
{
}

D* A::getD() { return d; }

基类外声明最好放在cpp文件中声明,不然其他地方引用头文件,可能会报重定义错误

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值