c++ - 带有 const 参数的友元函数
问题描述
我知道要创建一个友元函数,友元函数应该在封闭范围内显式声明或接受其类的参数。但是,这似乎是一个警告,我无法理解。为什么调用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
的对象是临时对象,不能绑定到非 const 的左值引用。
临时对象可以绑定到对 const 的左值引用(以及自 C++11 以来的右值引用),然后f2(99);
工作。并且可以将其复制到 的参数中f3
,然后f3(99)
也可以使用。
引用初始化的效果是:
否则,如果引用是对非易失性 const 限定类型的左值引用
or rvalue reference (since C++11)
:
- 否则,object 被隐式转换为 T。引用绑定到转换的结果
(after materializing a temporary) (since C++17)
。如果对象(或者,如果转换是通过用户定义的转换完成的,则转换函数的结果)的类型为 T 或从 T 派生,则它必须与 T 具有相同或更少的 cv 限定, and, if the reference is an rvalue reference, must not be an lvalue (since C++11)
。
推荐阅读
- java - 什么相当于 PHP 中的 Java 中的 preg_replace 和 base64_decode?
- c# - 在 C# 中使用 'ref' 或 'out' 常见做法
- haskell - 当我的 do 不为空时,为什么会出现“Empty do”错误?
- python - 更改文本组件的比例
- python - 如何在图像中找到数字的中心坐标
- python - 获取按 ID 分区的每个字段的非空数据
- node.js - 使用 koa-jwt 仅保护某些路由
- ios - 如何在 Realm Swift 中将一对一关系迁移到一对多关系
- c++ - C/++/ASM - 是否可以从 0x0 读取堆栈/堆大小和虚拟内存地址空间?
- android - 华为 Push Kit 错误:907135701:范围列表为空