c++ - 在哪里声明结构运算符重载

标签 c++ boost struct operator-overloading

我是C++的新手(我来自C#)。

我在命名空间中有这个结构:

#pragma once

namespace utils { 

    struct astTime
    {
        int hour;
        int min;
        double secs;
    };

    double round(double number, int decPlace);
}

我还有一个已实现round函数的源文件。

为了在Boost测试中使用该结构,我在Boost测试文件(.cpp)中定义了这两个运算符:
namespace utils {
    bool operator ==(utils::astTime const &left, utils::astTime const &right)
    {
        return(
            left.secs == right.secs
            && left.min == right.min
            && left.hour == right.hour);
    }

    std::ostream& operator<<(std::ostream& os, const utils::astTime& dt)
    {
        os << dt.hour << "h " << dt.min << "m " << dt.secs << "s" << std::endl;

        return os;
    }
}

我必须在哪里声明这两个运算符(以及如何声明)?

我已将其移至头文件(因为,我不知道将其声明为),请通过以下方式将它们从增强测试源文件中删除:
#pragma once
#include <iostream>

namespace utils { 

    struct astTime
    {
        int hour;
        int min;
        double secs;
    };

    bool operator ==(utils::astTime const &left, utils::astTime const &right)
    {
        return(
            left.secs == right.secs
            && left.min == right.min
            && left.hour == right.hour);
    }

    std::ostream& operator<<(std::ostream& os, const utils::astTime& dt)
    {
        os << dt.hour << "h " << dt.min << "m " << dt.secs << "s" << std::endl;

        return os;
    }

    double round(double number, int decPlace);
}

我收到以下错误:

warning LNK4006: "class std::basic_ostream > & __cdecl utils::operator<<(class std::basic_ostream > &,struct utils::astTime const &)" (??6utils@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV12@ABUastTime@0@@Z) already defined in Utils.obj; second definition ignored

最佳答案

您在代码中混合了声明和定义。将定义放入实现文件(*.cpp)。将声明放入 header 中round声明的旁边。

或者,您可以将定义放入 header 中并声明为 inline (这对于诸如自定义运算符之类的短函数来说是常规的)。函数上的inline说明符可防止函数在被多个翻译单元包含时违反One Definition Rule

关于c++ - 在哪里声明结构运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60042762/

相关文章:

c++ - 虚拟功能 : Iterating over a vector<Base Class> that is populated with subclass objects

c++ - 如何在找到某个单词后解析数字

c - 数组大小可变的结构

c - 如何在 C 中将结构体添加到结构体数组中?

c++ - 什么是 ios::in|ios::out?

c++ - 调用默认构造函数的两种方式

c++ - 重新解析具有相对 header 包含路径的ASTUnit失败

c++ - 创建库以覆盖迭代器的 operator*() - 风险悬空指针

c++ - boost 库中 float 和 double 的类型定义

c# - 在 C# : Vector, 方向(单位向量)、点中实现这 3 个类的最佳方式