C++基础知识

您所在的位置:网站首页 定义一个模板函数或模板类时要用到的第一个c C++基础知识

C++基础知识

2023-08-15 17:14| 来源: 网络整理| 查看: 265

1. 所有的类模板函数写在类的外部,在一个cpp中 #include #include using namespace std; template class Demo { public: Demo(T data = 0); //构造函数 Demo operator+(const Demo& other); //对象的data相加,返回一个对象 T getData() const; //获取data private: T data; }; //在类的实现文件里,需要声名类模板 template //类的作用域前添加 Demo::Demo(T data) { this->data = data; } template //类的返回值,类的作用域,类的形参都需要添加模板声明 Demo Demo::operator+(const Demo& other) { Demo tmp; tmp.data = (this->data + other.data); return tmp; } template T Demo::getData() const { return this->data; } int main(void) { Demo d1(100), d2(200); Demo tmp = d1 + d2; cout this->data = data; } template //类的返回值,类的作用域,类的形参都需要添加模板声明 Demo Demo::operator+(const Demo& other){ Demo tmp; tmp.data = (this->data + other.data); return tmp; } template T Demo::getData() const{ return this->data; }

main.cpp

#include #include #include "Demo.cpp" //需要包含类的实现.cpp文件 #include "Demo.h" using namespace std; int main(void) { Demo d1(100), d2(200); Demo tmp = d1 + d2; cout


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3