gpt4 book ai didi

c++ - 为什么可以临时调用成员函数而全局函数不能?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:19:45 25 4
gpt4 key购买 nike

在下面的代码中,我将 step 作为成员函数和临时值的全局函数调用。成员函数是允许的,并且可以工作,而全局函数是不允许的,因为 从类型为“kludge”的右值初始化类型为“kludge&”的非常量引用无效

我试图从语言的角度理解为什么允许一种行为而不允许另一种行为。从技术上讲,调用和函数似乎会以相同的方式编译,或者至少可以。

#include <iostream>

struct kludge {
int a;
kludge() {
a = 1;
}

kludge & step() {
a++;
std::cout << a << ",";
return *this;
}
};

kludge get() {
kludge t;
return t;
}

kludge & step( kludge & t ) {
t.a++;
std::cout << t.a << ",";
return t;
}

int main() {
get().step();
step( get() );
}

最佳答案

您不能将右值绑定(bind)到非常量左值引用1。这适用于 step(get()) 作为 step 的参数,它是一个非常量左值引用,不能绑定(bind)到纯右值(纯右值) get()

但是,成员函数本身可以在每个值类别的对象参数上调用,无论是左值还是右值 - [over.match.funcs]/4 和/5:

For non-static member functions, the type of the implicit object parameter is

  • “lvalue reference to cv X” for functions declared without a ref-qualifier or with the & ref-qualifier

[..]

For non-static member functions declared without a ref-qualifier, an additional rule applies:

  • even if the implicit object parameter is not const-qualified, an rvalue can be bound to the parameter as long as in all other respects the argument can be converted to the type of the implicit object parameter. [ Note: The fact that such an argument is an rvalue does not affect the ranking of implicit conversion sequences (13.3.3.2). — end note ]

但是如果您使用所谓的ref-qualifiers,您可以限制对特定成员函数有效的值类别。也就是说,如果你写:

kludge & step() & { /* .. */ }

调用 get().step() 也将是错误格式的。


1)
这是众所周知的事实,但这里是 [dcl.init.ref]/5,大幅缩短:

A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows:

  • If the reference is an lvalue reference and the initializer expression
    • is an lvalue [..]
    • has a class type (i.e., T2 is a class type), where T1 is not reference-related to T2, and can be implicitly converted to an lvalue of type “cv3 T3,” [..]

  • Otherwise, the reference shall be an lvalue reference to a non-volatile const type (i.e., cv1 shall be const), or the reference shall be an rvalue reference.

关于c++ - 为什么可以临时调用成员函数而全局函数不能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27678257/

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