C++ 存储两个类对象之间的差异

标签 c++

我想存储同一类的两个对象之间的差异。 我知道我可以覆盖 operator== 来比较两个对象。

我现在想知道是否有比以下示例更好的方法来获取两个对象之间的差异:

class ExampleClass {
public:
    ExampleClass();

    friend std::vector<std::string> compare(const ExampleClass& other) {
        std::vector<std::string> result;
        if(attribute1_ != other.attribute1_) {
            result.push_back("attribute1_");
        }
        // continue for other attributes
        return result;
    }

private:
    std::string attribute1_;
    int attribute2_;

在那个例子中,我必须比较每个属性。

最佳答案

我不是模板专家,所以我将展示如何使用宏来简化您的任务。

首先你定义宏是这样的:

#define COMP_ATTR(attr) \
    if (attr != other.attr) { \
        result.push_back(#attr); \
    }

然后你可以像这样重写你的比较函数:

friend std::vector<std::string> compare(const ExampleClass& other) {
    std::vector<std::string> result;
    COMP_ATTR(attribute1_);
    // continue for other attributes
    return result;
}

关于C++ 存储两个类对象之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56863751/

相关文章:

c++ - 重载转换函数模板

c++ - 使用 ReadDirectoryChangesW C++ 重命名文件夹后获取旧名称和新名称

c++ - 在 C++ 结构创建中执行更快

c++ - 自组织图 (SOM) 实现

c++ - ' ' 标记简单错误之前的预期主表达式

c++ - 如何将二维数组作为只读传递给双指针函数?

c++ - 开始使用 Crypto++

C++ - 错误 C3646 : unknown override specifier

c++ - 通用成员函数指针作为另一个类中的模板参数

c++ - Qt Creator 在新项目中显示错误,但代码编译正常