栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++基础-补漏日记8(类模板继承、类外、外文件、友元。写个数组)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++基础-补漏日记8(类模板继承、类外、外文件、友元。写个数组)

目录

1 类模板与继承

2 类模板成员函数类外实现

3 类模板分文件编写

4 类模板友元

5 用模板类写一个数组

运行结果

代码


类模板与继承

·看图推断,sonx;  int先传给子类的T1,string传给子类的T2,而T2是父类的T。

·父类是类模板,子类要明确标明父类T的数据类型。

类模板成员函数类外实现

加模板参数列表

 类模板分文件编写

类模板文件.hpp(约定好写hpp)

源文件.cpp

类模板友元

建议在类内实现 

用模板类写一个数组

运行结果

(1)数组操作-整型

(2)数组操作-类

(3)数组“=”


(1)类中不能调用类里写好的成员函数

 (2)运算符重载=和拷贝构造函数 在函数大部分相似。运算符重载要先析构对象和返回对象指针。


代码

源.cpp

#include
using namespace std;
//#include
#include"类模板.hpp"


class Student {
public:
	Student() {};
	Student(int age_) {
		this->age = age_;
	}
	int age;
};
void Print_Arr(MyArray&arr) {
	for (int i = 0; i < arr.get_size(); i++) {
		cout << arr[i].age << endl;
	}
}

void test() {
	cout << "普通构造" << endl;
	MyArray stu(2);
	Student a(18);
	Student b(28);
	Student c(38);
	stu.insert(a);
	stu.insert(b);
	stu.insert(c);
	stu[1] = stu[0];//把28赋值给18的
	Print_Arr(stu);

	
}
int main() {
	test();
}

类模板.hpp

#include
using namespace std;
#include
template
class MyArray {
	T* p;//堆区开辟的数组
	int Capacity;//数组容量
	int size;//数组大小
public:
	//构造
	MyArray(int cap) {
		this->Capacity = cap;
		this->size = 0;
		this->p = new T[this->Capacity];
		cout << "MyArray的构造函数" << endl;
	}
	//拷贝构造
	MyArray(const MyArray &arr) {
		this->Capacity = arr.Capacity;
		this->size = arr.size;
		this->p = new T[this->Capacity];
		for (int i = 0; i < this->size; i++) {
			this->p[i] = arr.p[i];
		}
		cout << "MyArray的拷贝构造函数" << endl;
	}
	//运算符重载“=”
	MyArray& operator=(const MyArray& arr) {
		if (this->p != NULL) {
			delete[] this->p;
			this->p = NULL;
			this->size = 0;
			this->Capacity = 0;
		}
		this->Capacity = arr.Capacity;
		this->size = arr.size;
		this->p = new T[this->Capacity];
		for (int i = 0; i < this->size; i++) {
			this->p[i] = arr.p[i];
		}
		cout << "MyArray的运算符重载函数" << endl;
		return *this;
	}
	//析构
	~MyArray() {
		if (this->p != NULL) {
			delete[] this->p;
			this->p = NULL;
		}
		cout << "MyArray的析构函数" << endl;
	}
	//数组操作
	//尾插法
	void insert(const T &val) {
		if (this->size == this->Capacity) {
			cout << "尾增法:已满" << endl;
			return;
		}
		this->p[this->size] = val;
		this->size++;
	}
	//尾删法
	void pop() {
		if (this->size == 0) {
			cout << "尾删法:无元素" << endl;
			return;
		}
		this->size--;
	}
	T& operator[](int index){
		return this->p[index];
	}
	//遍历
	void all() {
		for (int i = 0; i < this->size; i++)
			cout << this->p[i] << endl;
	}
	int get_size() {
		return this->size;
	}
	int get_capacity() {
		return this->Capacity;
	}
};

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1022273.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号