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引入的语法,它告诉编译器为该函数生成一个默认的实现版本。
    • 该虚析构函数没有函数体,编译器将为它生成一个默认的空实现
相关推荐
感哥14 小时前
C++ 面向对象
c++
沐怡旸15 小时前
【底层机制】std::shared_ptr解决的痛点?是什么?如何实现?如何正确用?
c++·面试
感哥1 天前
C++ STL 常用算法
c++
saltymilk1 天前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥1 天前
C++ lambda 匿名函数
c++
沐怡旸2 天前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥2 天前
C++ 内存管理
c++
博笙困了2 天前
AcWing学习——双指针算法
c++·算法
感哥2 天前
C++ 指针和引用
c++
感哥2 天前
C++ 多态
c++