Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How cast C++ class to intrinsic type

Basic C++ class question:

I have simple code currently that looks like something like this:

typedef int sType;
int array[100];

int test(sType s)
{
  return array[ (int)s ];
}

What I want, is to convert "sType" to a class, such that the "return array[ (int)s ]" line does not need to be changed. e.g. (pseudocode)

class sType
{
  public:
    int castInt()
    {
      return val;
    }
    int val;
}


int array[100];    
int test(sType s)
{
  return array[ (int)s ];
}    

Thanks for any help.

like image 593
Sam Avatar asked Dec 17 '10 11:12

Sam


People also ask

How does type casting work in C?

In type casting, the compiler automatically changes one data type to another one depending on what we want the program to do. For instance, in case we assign a float variable (floating point) with an integer (int) value, the compiler will ultimately convert this int value into the float value.

How do you cast a variable in C++?

Typecasting in C and C++ Typecasting is making a variable of one type, such as an int, act like another type, a char, for one single operation. To typecast something, simply put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable.

How do you convert an int to a double in C++?

int a{5},b{2},c{9}; double d = (double)a / (double)b + (double)c; int a{5},b{2},c{9}; double d = 1.0*a / b + c; The rules of precedence and implicit conversion will cause all the variables to be converted to doubles.

What do you mean by casting a data type?

A data type that can be changed to another data type is castable from the source data type to the target data type. The casting of one data type to another can occur implicitly or explicitly. The cast functions or CAST specification (see CAST specification) can be used to explicitly change a data type.


1 Answers

class sType
{
public:
    operator int() const { return val; }

private:
    int val;
};
like image 74
Alexandre C. Avatar answered Oct 02 '22 17:10

Alexandre C.