Automatic conversion and forced type replacement of C++ classes

Automatic conversion and forced type replacement of C++ classes

0X00 Foreword

In C++, the design of a class is a very important thing. The design of a class depends on whether its interface is good, that is, the design of the function.

Sometimes we may need to design a variety of interfaces in order to enhance the polymorphism of the class.

Today we will talk about the problem of transformation

Before that, let's define a class as our

class Dog
{
    
    
privateint GoOutTimes;  //表示一周遛狗的次数
   double Kilo;		//表示一周遛狗走的公里数
   double Time;		//表示一周遛狗的时间
public:
	Dog(double ti);  //构造函数:初始化遛狗时间
	Dog(int times,double ki);   //构造函数:初始化遛狗次数与遛狗距离
	Dog();		//默认构造函数Dog();	//析构函数

	void show_Ki() const;  //展示公里数
	void show_ti() const;  //展示时间
}

0X10 Automatic conversion during initialization

1. Using the implicit conversion of the constructor As
you can see, the above class provides three constructors:

    Dog(double ti);  
	Dog(int times,double ki);   
	Dog();		

We can call the constructor to initialize the class object when we declare it:

   Dog Chichi(12.6);
   Dog Mimi(3,10.2);
   Dog Lolo();

Because a Dog object represents a dog’s weekly outing situation (days, kilometers and time), can we provide some methods to convert integers or floating point numbers into Dog objects?

Since we have the corresponding constructor:
Dog(double ti);
so we can use the constructor to convert the double type to the Dog type. Isn't it weird?

However it does work

Dog myDog;
myDog=14.3;

When the program runs to myDog=14.3;, the compiler will check if there are constructor Dog(double)this constructor, since there is, then use Dog(double)to create atemporaryDog object, and then adopt one by one, members of the temporary assignment to copy the object to the myDog, this process is called implicit conversion , because it is done automatically.

One thing we need to pay special attention to
Only a constructor that accepts one parameter can be used as a conversion function

That Dog(int times,double ki);function is not used for conversion, unless it can provide a default value for the second argument :

Dog(int times,double ki=8.9); 

Only then can the user convert int

2. Explicit under explicit restriction

But sometimes in order to ensure safety, it is necessary to prevent this unsafe behavior from happening. (Does it sound contradictory, but this is exactly what language designers need to consider)

In other words, turn off this implicit conversion

Therefore, the introduction of explicit(explicit) qualifiers, under its modification, indicates that for the modified function, such implicit conversion will not work:

explicit Dog(double ti);  

At this time, the above implicit conversion will not work, but the explicit conversion can still be used to force the conversion:

Dog myDog;
//error
myDog = 13.2 
//right
myDog = Dog(13.2);
myDog = (Dog) 13.2;

3. Summary

To summarize just was talking about:
the use of explicitthe keyword Dog (double)can only be used to explicitly cast;
otherwise, can also be used for the following implicit conversions:

  • When initializing a Dog object to a double value

  • When passing a double value to a Dog object

  • When passing a double value to a function that accepts a Dog parameter

  • When the return value is declared as a function of Dog and tries to return a double value

  • In any of the above cases, when using a built-in type that can be converted to a double type

    Perhaps the last point is not clear to everyone.
    We take an example, took the uppermost class, there is Dog(double ti);a constructor, we all know, the double conversion type is possible to Dog:

Dog myDog;
myDog = 14.5;

However, the following code is also possible:

Dog myDog;
myDog = 14;

In fact, it is also very easy to understand because the int (14) type can be converted to the double (14.0) type, so this is legal.

But we should also pay special attention to: ambiguity

What does that mean?

Dog class if we have such a function Dog(long), then the myDog=14conversion will be invalid!

Because int can be converted to double or long, there is an ambiguity problem that makes the compiler difficult.

Then the compiler will strike.

0X11 custom conversion function

We mentioned above that we can convert basic types (such as double) into our class objects, provided that there is a corresponding constructor.

So, can the class object be directly converted to a basic type? (It sounds like a very strange idea again), like this:

Dog Nana(7.6);
double Time=Nana;

The answer is yes!

However, what we need at this time is not a constructor, but a special operator function——Conversion function

So how to create a conversion function?
Suppose we want to convert to typeName type, we need to use this form of conversion function:
operator ypename ()
Note the following:

  • The conversion function must be a class method;

  • The conversion function cannot specify the return type;

  • The conversion function cannot have parameters;

    Now we add the functions for converting Dog objects into int and double types to the class declaration:

class Dog
{
    
    
privateint GoOutTimes;  //表示一周遛狗的次数
   double Kilo;		//表示一周遛狗走的公里数
   double Time;		//表示一周遛狗的时间
public:
	Dog(double ti);  //构造函数:初始化遛狗时间
	Dog(int times,double ki);   //构造函数:初始化遛狗次数与遛狗距离
	Dog();		//默认构造函数Dog();	//析构函数

	void show_Ki() const;  //展示公里数
	void show_ti() const;  //展示时间

	operator int() const;	//转换为 int
	operator double() const;  //转换为 double

The implementation content of the function can be specified by yourself:

//将遛狗天数返回加1
Dog::operator int() const
{
    
    
	return GoOutTimes+1;
}

//返回一周遛狗平均公里数
Dog::operator double() const
{
    
    
	return Kilo/7;
}

0X20 Afterword

In order to expand the polymorphism of classes, C++ provides a lot of methods for designing classes. If we can use them well, it will be very helpful to our coding work.

I hope today’s content can be helpful to everyone~

Thank you all~

See you tomorrow!

———————————————————————————————————————————————— ——————
Reference: "C++ Primer Plus 6th Edition"

Guess you like

Origin blog.csdn.net/rjszz1314/article/details/104526762