首页 > 解决方案 > 带有 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);
}

标签: c++referenceconst-reference

解决方案


您正在使用参数调用函数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)

推荐阅读