简体   繁体   English

了解操作员重载的问题

[英]Problem in understanding operator overloading

I am reading TCPPPL by Bjarne Stroustrup and I came across the following piece of code (shown below). 我正在阅读Bjarne Stroustrup的TCPPPL,并且遇到了以下代码(如下所示)。 I have two questions: 我有两个问题:

  1. Where is the body of the function operator+? 函数operator +的主体在哪里? I mean there is only the declaration of the function in class X. 我的意思是在类X中只有函数的声明。

  2. What does the line X(int) mean? X(int)行是什么意思? Is this the constructor with int as a parameter or something else? 这是将int作为参数的构造函数吗?


 class X {
     public:
     void operator+(int);
     X(int);   
 };

 void operator+(X,X);
 void operator+(X,double);

 void f(X a)
 {
     a+1;    // a.operator+(1)
     1+a;    // ::operator+(X(1),a)
     a+1.0;  // ::operator+(a,1.0)
 }

What does the line X(int) mean? X(int)行是什么意思?

X(int) is a declaration of a constructor accepting a single integer parameter. X(int)是接受单个整数参数的构造函数的声明。 Definition is missing. 缺少定义。

Where is the body of the function operator+ 函数操作符的主体在哪里?

Wherever you defined it. 无论您在哪里定义它。

This code won't work without the correct definitions. 没有正确的定义,该代码将无法工作。

1) Where is the body of the function operator+? 1)函数operator +的主体在哪里? I mean there is only the declaration of the function in class X. 我的意思是在类X中只有函数的声明。

The definition (body) of operator+ can be anywhere. operator+的定义(主体)可以在任何地方。 The code is obviously not a complete program (there is no main ). 该代码显然不是一个完整的程序(没有main )。 Therefore, the definitions might be below the shown code or even in another compilation unit. 因此,定义可能在显示的代码下面,甚至在另一个编译单元中。

2) What does the line X(int) mean? 2)X(int)行是什么意思? Is this the constructor with int as a parameter or something else? 这是将int作为参数的构造函数吗?

This is a declaration of a converting constructor of class X that accepts an integer as an argument. 这是类X的转换构造函数的声明,该构造函数接受整数作为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM