一个C++类模板练手的例子

此博客主要是关于C++类模板的练手实践,不过强调了该实践纯粹为练手,并无实际意义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 纯粹练手,没有任何实际意义。

#include <iostream>

using namespace std;

template <class T, int size>
class HelloA{
public:
	HelloA() {
		cout << "Hello, World!\n";
	}
	char* print(float x, T t);
	HelloA(short x, int y, T t);
protected:
	short x;
private:
	int y;
	T t;
};

template <class T, int size>
HelloA<T, size>::HelloA(short x, int y, T t){
		this->x = x;
		this->y = y;
		this->t = t;
		y = size;
}

template <typename T, int size>
char* HelloA<T, size>::print(float x, T t){
//因为没有对<<操作符进行重载,所以这里t应该定义为一个基本类型。
//否则产生异常。
	cout << "x = " << x << "\t\t" << "t = " << t << endl;
}

template <class T>
class HelloB:public HelloA<const char*, 100> {
public:
	HelloB():HelloA(){}
	HelloB(short x, int y, T t):HelloA(x , y , t){}
protected:
private:
};

int main(void) {
	HelloB<const char*> hellob;
	hellob.print(25, "print() Hello, World!");
	HelloA<int, 100> helloa(20, 20, 100);
	helloa.print(3.3, 20);
	HelloB<const char*> hb(2, 30, "GOOD!\n");
	hb.print(200, "HAPPY EVERY DAY!");
}

/*
C:\Users\Administrator>g++ -o MyClass.exe MyClass.cpp

C:\Users\Administrator>MyClass
Hello, World!
x = 25          t = print() Hello, World!
x = 3.3         t = 20
x = 200         t = HAPPY EVERY DAY!
*/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_39410618

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值