C++测试代码

C++测试代码

目录

基于C++实现的AOP功能

cpp 复制代码
#include <iostream>
#include <string>

struct LogHeader {
    std::string prefix;
    std::string aspect;
};

template <typename T>
void before(const std::string& msg, const LogHeader& header) {
    std::cout << header.prefix << " [" << header.aspect << "]: Before " << msg << std::endl;
}

template <typename T>
void after(const std::string& msg, const LogHeader& header) {
    std::cout << header.prefix << " [" << header.aspect << "]: After " << msg << std::endl;
}

// 抽象基类代替接口
class MessageService {
public:
    virtual ~MessageService() = default;
    virtual std::string getMessage() = 0; // 纯虚函数
};

class MessageServiceImpl : public MessageService {
public:
    std::string getMessage() override {
    	std::cout << "Hello, World!" << std::endl;
        return "Hello, World!";
    }
};

template <typename T>
class LoggingWrapper : public T {
    LogHeader header;

public:
    LoggingWrapper(const LogHeader& h) : header(h) {}

    template <typename... Args>
    LoggingWrapper(const LogHeader& h, Args&&... args) : T(std::forward<Args>(args)...), header(h) {}

    std::string getMessage() {
        before<LoggingWrapper<T>>("getMessage", header);
        std::string result = T::getMessage();
        after<LoggingWrapper<T>>("getMessage", header);
        return result;
    }
};

int main() {
    LogHeader header = {"MyApp", "Logging"};
    LoggingWrapper<MessageServiceImpl> service(header);
    service.getMessage();
    return 0;
}
  • 说明:
    • 以上代码由claude ai生成,经测试正常运行
    • ~MessageService()是MessageService类的析构函数,用于在对象被销毁时执行必要的清理工作。
    • virtual关键字的作用是使该析构函数在继承层次中有多态行为。这意味着当我们通过基类指针/引用删除派生类对象时,将自动调用正确的派生类析构函数。
    • = default是C++11引入的语法,它告诉编译器为该函数生成一个默认的实现版本。
    • 该虚析构函数没有函数体,编译器将为它生成一个默认的空实现
相关推荐
大可不必了1 小时前
03 函数定义和调用
开发语言·python
I_belong_to_jesus1 小时前
C++关于分支预测的优化1
开发语言·c++·算法
承渊政道2 小时前
【Python编程—从入门到实践】(记分与闯关:用Python+Pygame,打造越战越精彩的太空大战!)
开发语言·python·pycharm·游戏程序·pygame
爱学习的程序媛2 小时前
Python常用框架梳理
开发语言·后端·python·ai·web·后端框架·python框架
Rabitebla2 小时前
【Linux】进程控制(十二) 自定义 Shell(二):内建命令与进程工作目录管理
linux·c++·笔记·学习·bash
eggwyw4 小时前
Anaconda安装卸载的详细流程指南
开发语言·python
码客-ygluu8 小时前
一个通用游戏数据服务器
c++·架构
another heaven8 小时前
【C/C++ Ranges 是零开销抽象吗?拆开管道、惰性求值和编译期膨胀】
c语言·开发语言·c++
SomeOtherTime9 小时前
Rust 闭包语法和原理(AI回答)
开发语言·后端·rust
apcipot_rain10 小时前
C++转Java日记(10)
java·开发语言