为什么会发生这种转换

Why is this conversion happening?

本文关键字:转换 为什么      更新时间:2023-10-16
#include<iostream>
using namespace std;
class test
{
  int a, b;
public:
  test() {
    a=4; b=5;
  }
  test(int i,int j=0) {
    a=i; b=j;
  }
  test operator +(test c) {
     test temp;
     temp.a=a+c.a;
     temp.b=b+c.b;
     return temp;
  }
  void print() {
    cout << a << b;
  }
};
int main() {
  test t1, t2(2,3), t3;
  t3 = t1+2;
  t3.print();
  return 0;
}

编译器如何接受像t3=t1+2;这样的语句,其中2不是对象?

编译器

看到您正在调用operator+(test),并尝试使用 test(int i,int j=0) 构造函数成功将2隐式转换为test

如果要显式转换,则必须将构造函数更改为 explicit test(int i, int j=0) 。在这种情况下,您的代码将生成编译器错误,因为2无法隐式转换为 test 。您需要将表达式更改为 t1 + test(2)

因为test(int i,int j=0)是一个接受一个或两个参数的构造函数,所以test对象是从2创建的。在下一阶段,test operator +(test c)被调用。

有一个二进制operator+可用,它需要两个类型 test 的操作数。此外,test可以通过构造函数test(int, int = 0)int隐式构造。将两者放在一起,t1 + 2变得t1 + test(2, 0) .

要禁止这种静默转换(有时会导致非常令人惊讶的转换链(,请将接受单个参数的构造函数声明为显式参数:explicit test(int, int = 0)

因为test(int i, int j = 0)没有明确标记。

因此,t1 + 2被解释为t1.operator+(2)而它本身被解释为t1.operator+(test(2))(隐式转换(。

如果将构造函数标记为 explicit ,则(在编译期间(将发生错误,指出2无法转换为testoperator+不匹配。

简而言之,由于C++包括运算符重载,因此能够为用户定义类型定义运算符的自定义实现。上面显示的operator+()函数是定义类型 test+运算符的方式。当编译器看到+应用于test对象的表达式时,它会查找在test中定义的operator+(或定义为全局函数的双参数形式,其第一个参数类型为 testtest& (。然后,它可能在转换另一个参数后调用该函数。

因为构造函数test(int i,int j=0)引入了从inttest的用户定义转换。

编译器使用其构造函数创建 Test 类型的对象。

 t3 = t1 + test(2);
相关文章: