Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are different conversion functions for int and const int allowed?

Why is the following allowed to be compiled in C++?

#include<iostream> using namespace std;  class mytest { public:         operator int()     {         return 10;     }      operator  const int()     {         return 5;     } };  int main() {     mytest mt;     //int x = mt;    //ERROR ambigious      //const int x = mt; //ERROR ambigious } 

Why does it make sense to allow different versions (based on constness) of the conversion operator to be compiled when their use always results in ambiguity?

Can someone clarify what I am missing here?

like image 789
code707 Avatar asked Jun 20 '18 09:06

code707


People also ask

What is the difference between const int and int const?

So in your question, "int const *" means that the int is constant, while "int * const" would mean that the pointer is constant. If someone decides to put it at the very front (eg: "const int *"), as a special exception in that case it applies to the thing after it.

What is the difference between int * const C and const int * C?

const int * And int const * are the same. const int * const And int const * const are the same. If you ever face confusion in reading such symbols, remember the Spiral rule: Start from the name of the variable and move clockwise to the next pointer or type.

Which of the following is the correct declaration for a constant pointer to an int datatype?

int *const is a constant pointer to integer This means that the variable being declared is a constant pointer pointing to an integer.

What does const int mean in C++?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.


1 Answers

For conversion they're ambiguous; but you might call them explicitly. e.g.

int x = mt.operator int(); const int x = mt.operator const int(); 
like image 153
songyuanyao Avatar answered Oct 12 '22 22:10

songyuanyao