C++ 类、方法的同一声明不同实现的方式

问题提出

  • 头文件:声明CurrentTime类和PrintTime方法。
#ifndef CURRENT_TIME_H
#define CURRENT_TIME_H
class CurrentTime {
public:
    void PrintTime();
};
#endif
  • main函数:创建CurrentTime对象,调用PrintTime。
#include "current_time.h"

int main()
{
    CurrentTime t;
    t.PrintTime();
    return 0;
}

提问:如何使得t.PrintTime()有不同的功能?

解决方案

编译阶段

通过编译宏在编译阶段选择不同源码,实现不同的功能。

  • cpp文件
#include "current_time.h"
#include <iostream>
void CurrentTime::PrintTime()
{
#ifdef RUN_TIME
    std::cout << "运行时间" << std::endl;
#endif
#ifdef CURRENT_TIME
    std::cout << "本地时间" << std::endl;
#endif
}

CMakeList.txt文件:通过定义不同的编译宏,决定需要的功能。

# add_definitions(-DCURRENT_TIME)
add_definitions(-DRUN_TIME)

# 给工程添加一个可执行程序
add_executable(${PROJECT_NAME} 
    main.cpp
    current_time.cpp
)

链接阶段

每个.cpp文件为一个编译单元,生成一个可重定位的目标文件(.o文件) 。链接阶段,通过链接不同的目标文件,实现类或者方法的不同实现。

  • local_time.cpp
#include "current_time.h"
#include <iostream>

void CurrentTime::PrintTime()
{
	std::cout << "本地时间" << std::endl;
}
  • run_time.cpp
#include "current_time.h"
#include <iostream>

void CurrentTime::PrintTime()
{
	std::cout << "运行时间" << std::endl;
}

CmakeList.txt文件,可执行文件链接不同的目标文件,实现PrintTime的定制化实现。

# set(current_time local_time.cpp)
set(current_time run_time.cpp)

# 给工程添加一个可执行程序
add_executable(${PROJECT_NAME} 
    main.cpp
    ${current_time}
)

动态加载阶段

libcurrent_time.so用于实现打印时间的功能,具体打印本地时间还是系统时间,取决于生成动态库的源码为local_time.cpp还是run_time.cpp。多数情况下local_time.cpp和run_time.cpp处于不同的产品定制化代码仓内,不同的定制化代码仓都会生成libcurrent_time.so动态库,但其实现的功能不同。

# 给工程添加一个可执行程序
# 给工程添加一个可执行程序
add_executable(${PROJECT_NAME} 
    main.cpp
    # ${current_time}
    # current_time.cpp
)
# 生成库
add_library(current_time SHARED local_time.cpp) 
# add_library(current_time SHARED run_time.cpp) 
# 给工程链接库
target_link_libraries(${PROJECT_NAME} current_time)

在这里插入图片描述

运行阶段

运行阶段可以通过读取配置文件的内容来判断需要执行的功能。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值