gpt4 book ai didi

c++ - 将对象分配给方法调用

转载 作者:太空狗 更新时间:2023-10-29 20:49:09 25 4
gpt4 key购买 nike

我有一个名为 YourClass 的类(class)。我的问题是为什么编译器不会为以下代码生成错误?

YourClass AMethod(){ return YourClass();}
AMethod() = YourClass();

[在这种情况下,在我看来,方法只是返回一个值(我的意思是它没有左值)。]

编辑:如果我能做到以上几点,为什么我不能做到以下几点

int AMethod(){ return a;}
AMethod() = 5;

最佳答案

EDIT1:我想我第一次理解这个问题。

标准说:3.10 左值和右值

The result of calling a function that does not return a reference is an rvalue. User defined operators are functions, and whether such operators expect or yield lvalues is determined by their parameter and return types.

除了用户定义类型和原始类型相同之外,标准在本段中什么也没说。如果函数的返回值不是引用,那么它就不是左值。然而,同一页面上有一个有趣的评论:

47) Expressions such as invocations of constructors and of functions that return a class type refer to objects, and the implementation can invoke a member function upon such objects, but the expressions are not lvalues.

所以基本上在你的例子中:

AMethod() = YourClass();

AMethod 返回一个用户定义的类型,其函数:

AMethod().operator=(YourClass());

被执行。尽管如此,它仍然不是左值。事实上,您可以在 C++ 中使用空语句,或者只包含右值的语句!:

5;;; // correct C++ code!

编辑 2:

考虑这个例子:

if( &(YourClass() + YourClass()) == &YourClass() )
{
....
}

表达式 &(YourClass() + YourClass()) 必须产生一个左值,这样整个表达式才正确。它在 VC 上编译得很好,但它给出了这个小警告:

warning C4238: nonstandard extension used : class rvalue used as lvalue

显然上面这行代码是 C++ 标准错误的,但 VC 允许它!


因为你是这么问的。首先,AMethod 返回一个新的 YourClass 实例。然后,它被分配另一个新实例。当然在 C++ 中你可以说任何你想说的。因此,要防止赋值语句,只需返回 const YourClass。在这种情况下,该对象仅变为“可读”:

const YourClass AMethod(){ return YourClass();}

这与重载二元运算符的情况相同。例如,如果您为一个类重载 operator+,那么您可以使用 const 或不使用它。

// '+' operator is defined as a friend operator not a member.
friend YourClass operator+(const YourClass& lhs, const YourClass& rhs)
{
...
}

如果你那样做,你可能会得到如下无意义的语句:

(a + b) = c;

表达式 (a + b) 没有用,因为它只表示一个值,而不是我们控制的变量,它会生成一个临时变量。

关于c++ - 将对象分配给方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1506727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com