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

范思法兰

我是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);
}

我收到以下错误:

警告LNK4006:“类std :: basic_ostream>&__cdecl utils :: operator <<(类std :: basic_ostream>&,struct utils :: astTime const&)”(?? 6utils @@ YAAAV?$ basic_ostream @ DU?$ Utils.obj中已定义的char_traits @ D @ std @@@ std @@ AAV12 @ ABUastTime @ 0 @@ Z);第二个定义被忽略

康拉德·鲁道夫

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

或者,您可以将定义放入标头中并声明它们inline(这对于诸如自定义运算符之类的短函数来说是常规的)。inline从违反有关职能防止功能说明符的一个定义规则由多个翻译单位包括时。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章