C++ experiment---type variable class

**Topic Four: **Types of Variable Types

Description

Define a Data class that contains at least one data member of type int and one data member of double type, and define its constructor and destructor, so that when the program is executed, it can produce the results shown in the sample.

Input

Enter 2 lines, the first line is a data of type int, and the second line is a data of double type.

Output

See example.

Sample Input

120
3.14

Sample Output

A default object is created.
An integer object 120 is created.
A double object 3.14 is created.
The double object 3.14 is erased.
The integer object 120 is erased.
The default object is erased.

Given the main function of the title:

int main()
{
    
    
    Data d1;
    int i;
    cin>>i;
    Data d2(i);
    double d;
    cin>>d;
    Data d3(d);
    return 0;
}

code:

#include<iostream>
#include<string>
#include<string.h>
using namespace std;

class Data{
    
    
	int Int;
	double Dou;
	string type;
public:
	Data(){
    
    
		Int=0;
		Dou=0.0;
		type="default";
		cout<<"A default object is created."<<endl;
	}
	Data(int i){
    
    
		Int=i;
		Dou=0;
		type="integer";
		cout<<"An integer object "<<Int<<" is created."<<endl;
	}
	Data(double d){
    
    
		Dou=d;
		Int=0;
		type="double";
		cout<<"A double object "<<Dou<<" is created."<<endl;
	}
	~Data(){
    
    
		if(strcmp(type.c_str(),"default")==0){
    
    
			cout<<"The default object is erased."<<endl;
		}else if(strcmp(type.c_str(),"integer")==0){
    
    
			cout<<"The integer object "<<Int<<" is erased."<<endl;
		}else{
    
    
			cout<<"The double object "<<Dou<<" is erased."<<endl;
		}
	}//此处使用c_str()和data()都是可以的! 
};

int main()
{
    
    
    Data d1;
    int i;
    cin>>i;
    Data d2(i);
    double d;
    cin>>d;
    Data d3(d);
    return 0;
}

Functions of string:
1).data(): returns a string but does not end with'\0';
2).c_str(): returns a string and ends with'\0';

Guess you like

Origin blog.csdn.net/timelessx_x/article/details/115034153