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.
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.
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.
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.
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.
class sType
{
public:
operator int() const { return val; }
private:
int val;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With