运算符重载C ++放置 [英] Operator overloading c++ placement

查看:89
本文介绍了运算符重载C ++放置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在弄清楚我创建的重载运算符的放置位置时遇到麻烦.他们应该在他们所经营的班级中还是内部?两种方式都给我带来麻烦.任何指针都很棒.

Im having trouble figuring out where to place the overloaded operators i created. should they be in the class they operate on, or inside? both ways are causing me trouble. any pointers would be great.

这是我非常基本的uint128_t类:

here is my very basic uint128_t class:

class uint128_t{
    private:
        uint64_t UPPER, LOWER;

    public:
    // constructors
        uint128_t(){
            UPPER = 0;
            LOWER = 0;
        }

        template <typename T>
        uint128_t(T val){
            UPPER = 0;
            LOWER = (uint64_t) val;
        }

        template <typename S, typename T>
        uint128_t(const S & upper_val, const T & lower_val){
            UPPER = (uint64_t) upper_val;
            LOWER = (uint64_t) lower_val;
        }

        uint128_t(uint128_t val){
            UPPER = val.upper();
            LOWER = val.lower();
        }

        uint64_t upper(){
            return UPPER;
        }

        uint64_t lower(){
            return LOWER;
        }
};

如果操作员在课堂上,他们工作会很好.但是,我可以执行uint128_t ^ uint32_t,但不能执行uint32_t ^ uint128_t.另一方面,将所有内容移到外面给了我error: 'uint128_t operator=(uint128_t, T)' must be a nonstatic member function.同样,operator =显然不适用于恒定输入,因为值将是ULLL,除非有人知道这样做的方法,否则该值将不存在.

if the operators are in the class, they work fine. however, i can do uint128_t ^ uint32_t but not uint32_t ^ uint128_t. on the other hand, moving everything outside is giving me error: 'uint128_t operator=(uint128_t, T)' must be a nonstatic member function. also, operator= will not work for a constant input apparently, since the values will be ULLL, which doesnt exist, unless someone know of a way to do so.

我该怎么办?

推荐答案

为什么不将两者混合使用? 将operator =放到里面,其余的放到外面.

Why not a mix of both? Put operator= inside, and the rest outside.

对于那些以uint128_t作为左手参数的人来说,没关系,如果它是右手参数,那么它必须是一个全局函数.因此,如果这两个函数是全局的,则可以将它们并排放置.您甚至可能会避开一个聪明的宏,即使仅对交换宏,也可以对这两种都有一个实现.

For the ones that take uint128_t as left-hand-side argument it doesn't matter, if it's a right-hand-side argument then it has to be a global function. So for that reason you can put both functions side-by-side if they're global. You might even get away with a clever macro to have one implementation for both, if only for the commutative ones.

这篇关于运算符重载C ++放置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆