C++ experiment --- template is a good thing

Templates are a good thing

Description
defines the Point class:

There are two data members of type int, representing its horizontal and vertical coordinates.

No-argument constructor, initialize the two coordinates to 0.

Constructor with parameters.

Overload its output operator <<, which is used to output the abscissa and ordinate of a point, separated by a space.

Define a class template Data:

There is only one data member data, and the type of data is specified by the type parameter.

Define the constructor of this class template.

Define the void show() method to display the value of data.

Input
has 5 lines.

The first line is a string without whitespace.

Lines 2 to 4 are an integer respectively, and lines 2 and 3 are the coordinate values ​​of the points.

The last line is a character. See the example for
Output
.
Sample Input

test
1
2
3
c

Sample Output

c
3
test
1 2

code:

#include<iostream>

using namespace std; 
class Point{
    
    
	int x;
	int y;
public:
	Point(){
    
    
		x=0;
		y=0;
	}
	
	Point(int xx,int yy){
    
    
		x=xx;
		y=yy;
	}
	
	friend ostream& operator <<(ostream &os,const Point &P){
    
    
		os<<P.x<<' '<<P.y;
	}
};

template<class T>
class Data{
    
    
	T data;
public:
	Data(T t){
    
    
		data=t;
	}
	
	void show(){
    
    
		cout<<data<<endl;
	}
};


int main()
{
    
    
    string n;
    int x, y, d;
    char c;
    cin>>n;
    cin>>x>>y>>d;
    cin>>c;
    Point p(x, y);
    Data<char> aChar(c);
    Data<int> anInt(d);
    Data<Point> aPoint(p);
    Data<string> aString(n);
    aChar.show();
    anInt.show();
    aString.show();
    aPoint.show();
    return 0;
}

Guess you like

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