gpt4 book ai didi

c++ - 带有 const 参数的友元函数

转载 作者:行者123 更新时间:2023-12-01 14:48:06 24 4
gpt4 key购买 nike

我知道要创建一个友元函数,友元函数应该在封闭范围内显式声明或接受其类的参数。但是,这似乎是一个警告,我无法理解。为什么调用f1(99)不工作?

class X { 
public:
X(int i) {
std::cout << "Ctor called" << std::endl;
}
friend int f1(X&);
friend int f2(const X&);
friend int f3(X);
};
int f1(X& a) {
std::cout << "non-const called" << std::endl;
}
int f2(const X& a) {
std::cout << "const called" << std::endl;
}
int f3(X a) {
std::cout << "object called" << std::endl;
}

int main() {
f1(99);
f2(99);
f3(99);
}

最佳答案

您正在使用参数 99 调用函数;但所有函数都需要 X . 99可以转换为 X隐含地,但转换后的 X是一个临时对象,不能绑定(bind)到非常量的左值引用。

临时对象可以绑定(bind)到 lvalue-reference to const (以及从 C++11 开始的右值引用),然后是 f2(99);作品。并且可以复制到f3的参数中,然后 f3(99)也可以。

The effects of reference initialization are:

  • Otherwise, if the reference is lvalue reference to a non-volatile const-qualified type or rvalue reference (since C++11):

    • Otherwise, object is implicitly converted to T. The reference is bound to the result of the conversion (after materializing a temporary) (since C++17). If the object (or, if the conversion is done by user-defined conversion, the result of the conversion function) is of type T or derived from T, it must be equally or less cv-qualified than T, and, if the reference is an rvalue reference, must not be an lvalue (since C++11).

关于c++ - 带有 const 参数的友元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61363028/

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