【C++】类模板分离式写法

一.知识点概述

一种类型的实例共享一个静态成员(不论静态成员的类型是啥T/int/char/…)

\"为"的转义

二.示例

在这里插入图片描述

A.h

#pragma once
using namespace std;
#include <iostream>

template <typename T>
class A
{
public:
	A(T m_x = 0);//初始化构造函数

	A operator+ (const A& other);//类内+运算符重载,实现两对象相加,返回临时对象,保存结果

	T getM_x();

	template <typename T>//完全按照类外声明的写法
	friend A<T> operator-(const A<T>& a1, const A<T>& a2);//类外友元-运算符重载函数

	template <typename T>//完全按照类外声明的写法
	friend A<T> addA(const A<T>& a1, const A<T>& a2);//类外友元普通函数
	
    // 类外operator<<运算符重载函数:特别记忆!
    // 不写template,只<<后加<T>(定义/实现时要写template不加<T>)
	friend ostream& operator<< <T>(ostream& os, const A& object);

	static string s;
private:
	T m_x;
};

template <typename T>
string A<T>::s = "";

A.hpp

#include "A.h"

template<typename T>
inline A<T>::A(T m_x) :m_x(m_x) {}

template<typename T>
inline A<T> A<T>::operator+ (const A<T> & other) {
	A tmp;
	tmp.m_x = m_x + other.m_x;
	return tmp;
}

template<typename T>
inline T A<T>::getM_x() {
	return m_x;
}

template<typename T>
A<T> operator-(const A<T>& a1, const A<T>& a2)//类外友元函数为保证安全,不修改已有成员,最好加上const
{
	//a1.m_x -= a2.m_x;
	//return a1;//相加就不传递了,相等时才传递,为了方便连续赋值
	A<T> tmp;
	tmp.m_x = a1.m_x - a2.m_x;
	return tmp;
}

template<typename T>
A<T> addA(const A<T>& a1, const A<T>& a2)
{
	A<T> tmp;
	tmp.m_x = a1.m_x + a2.m_x;
	return tmp;
}

template <typename T>
ostream& operator<<(ostream& os, const A<T>& object) {
	os << object.m_x << endl;
	return os;
}

测试文件:

main.cpp

#include "A.hpp"

int main() {
	A<int> a1(1), a2(2);
	cout << a1;
	cout << (a1 + a2).getM_x() << endl;//仅调用无需实例化,创建新的对象才要实例化
	cout << addA(a1, a2).getM_x() << endl;
	
	A<int> a3 = a1 + a2;
	A<int> a4 = addA(a1, a2);//因为a1,a2已实例化,调用模板函数无需再次实例化
	A<int> a5 = addA<int>(a1, a2);

	cout << (a2 - a1).getM_x() << endl;//运算符重载函数的调用不用实例化
	
	A<float> a10, a11;
	A<long>  a20, a21;
	cout << "set <float>a10.s=\"float\"后:" << endl;
	a10.s = "float";
	cout << "<float>a11.s=" << a11.s << endl;
	cout << "<long>a21.s=" << a21.s << endl;

	cout << "set <long>a20.s=\"long\"后:" << endl;
	a20.s = "long";
	cout << "<float>a11.s=" << a11.s << endl;
	cout << "<long>a21.s=" << a21.s << endl;

	return 0;
}

输出效果:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值