Primitive datatypes in C++ are datatypes that are predefined in the language itself; like int, float, double, etc. Objects are instances of a class, and C++ being an object-oriented language, conversion between primitive data types and objects is necessary. A class serves as a data type's architectural plan. Although this doesn't describe any data specifically, it does specify what the class name signifies, i.e., what an object of the class will look like and what operations may be carried out on it.
在C++语言编译器中,原始数据类型到对象之间的转换没有明确定义,因此要将原始数据类型转换为对象,必须由程序员定义机制。如何将原始类型转换为特定对象是在用户定义类的构造函数中定义的。我们举一个例子来更好地理解这个问题。
The problem that we are solving is to convert a weight given in grams to kilograms and grams. For that, we have defined a user-defined class weight, that contains two integer members kg and gm. ‘kg’ is the kilogram value of the given weight and the ’gm’ is the weight remaining that is lesser than one kilogram to be converted. The algorithm to solve the problem is given below.
The syntax for the conversion is like below −
class Myclass{ private: int classVal; public: MyClass(){ classVal = 0; } MyClass(int val) { classVal = val; } }; int main() { Myclass m; int val = <integer value>; m = val; return 0; }
在定义的类的构造函数中,执行以下操作:
如前所述,所有的转换机制都必须在构造函数内定义。构造函数必须是带参数的,并且原始源值必须作为参数传递给构造函数。问题的源代码如下。
#include <iostream> using namespace std; //converts weight in grams to kgs and grams class Weight { private: int kg, gm; public: //default constructor Weight() { kg = 0; gm = 0; } //paramaeterized constructor Weight(int ip) { this->kg = ip / 1000; this->gm = ip % 1000; } //shows the output void show() { cout << "The weight is " << this->kg << " kgs and " << this->gm << " grams." << endl; } }; int main() { //weight in grams int ip = 1085; //conversion done here Weight w; w = ip; w.show(); return 0; }
The weight is 1 kgs and 85 grams.
In the example, the input is inside the main function as ‘ip’. There is also an object of class weight ‘w’. We have just assigned the integer value to the class object and an implicit call to the object’s parameterized constructor has been called. The functions defined in the constructor have been performed and at last, the output is displayed by calling the ‘show’ function.
In this example, the conversion from primitive type to user-defined class object is done using the implicit invocation of the constructor. This is fine until the constructor needs more than one primitive value to instantiate the object. For this reason, we have to explicitly invoke the constructor and then pass the primitive values as arguments to the object constructor. The opposite conversion from object to primitive types is different, it needs more complicated procedures to complete.