本文介绍了C ++分配给隐式转换的左值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下C ++代码段:

Consider this snippet of C++ code:

struct Foo {
    float value;

    operator float& () {
        return this->value;
    }
};

int main() {
    Foo foo;
    foo=1.0f;   //Doesn't compile, foo isn't implicitly converted to a float&

    return 0;
}

为什么不编译?是否有特定原因不包含在C ++标准中?还是确实存在等效项,而我只是在错误地使用它?

Why doesn't this compile? Is there a specific reason this wasn't included in the C++ standard? Or an equivalent does indeed exist and I'm just using it wrong?

推荐答案

对于几乎所有其他运算符,您的转换运算符

For pretty much all other operators, your conversion operator would do exactly what you want, and it would continue to do exactly what you want even if you add custom operators.

struct Foo {
    float value;
    operator float& () { return this->value; }
    Foo &operator+=(Foo);
};
int main() {
    Foo foo {};
    foo+=1.0; // compiles and works
    // equivalent to foo.operator float&()+=1.0;
}

但是, = 很特殊,与大多数其他运算符相比, = 的规则不同。由TC确认:

However, = is special, the rules for = are different compared to most other operators. As identified by T.C.:

4对于内置赋值运算符,按以下方式限制左操作数的转换:

(4.1)-不引入临时变量来保存左操作数,并且

(4.2)-没有将用户定义的转换应用于左操作数,以实现与内置候选的最左边参数的类型匹配。

4 For the built-in assignment operators, conversions of the left operand are restricted as follows:
(4.1) -- no temporaries are introduced to hold the left operand, and
(4.2) -- no user-defined conversions are applied to the left operand to achieve a type match with the left-most parameter of a built-in candidate.

结合不允许将任何自定义 operator = 定义为全局函数的事实,可以确保 foo = bar; 其中 foo 是一个类类型,始终表示 foo.operator =(bar); ,没别的。

Together with the fact that any custom operator= is not allowed to be defined as a global function, this makes sure that foo=bar; where foo is a class type always means foo.operator=(bar);, nothing else.

这个操作符被选出来的事实并不能说明原因,但可以很清楚地表明这是一个有意的决定,并确保 foo = bar; 始终表示 foo.operator =(bar); ,仅此而已,这似乎是一个正当的理由。

The fact that this one operator is singled out doesn't explain the reason, but does make it quite clear that it's an intentional decision, and making sure that foo=bar; always means foo.operator=(bar);, nothing else, by itself already seems like a valid reason.

这篇关于C ++分配给隐式转换的左值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 04:38