函数模板覆盖以及处理类的私有

来源:互联网 发布:seo屈臣氏优化方案 编辑:程序博客网 时间:2024/05/22 03:46

函数模板实现通用,可以根据自有数据类型,进行优化

结构体可以直接赋值(没有私有变量)

所有成员都是公有的类型可以赋值(一开始初始化)
如果类有私有成员变量,不可以用{}初始化

类的对象之间默认是可以直接赋值

类,结构体都有一个默认赋值操作= 浅拷贝 ,交换数据

深拷贝用的最多,函数模板的覆盖

#define _CRT_SECURE_NO_WARNINGS#include<iostream>#include<string>class info{public:    char name[40];    char *p;    int data;private:    int num;public:    void set(int X)    {        this->num = X;//通过接口设置私有变量    }    int get()    {        return this->num;//返回值,副本机制    }};template<typename T>void swap(T &a, T &b){    std::cout << "通用函数模板" << std::endl;    T temp = a;    a = b;    b = temp;//交换两个变量}//模板为空,明确类型,template<>void  swap(info &info1, info &info2){    std::cout << "特有函数模板" << std::endl;    //通用模板可以实现通用,针对自己的数据类型做出优化    //计数器,对象交换计数器    info temp = info1;    info1 = info2;    info2 = temp;    //}void main(){    info info1;    info info2;    std::strcpy(info1.name, "lbc");    std::strcpy(info2.name, "bcl ");    info1.data = 102;    info2.data = 201;//初始化    info1.p = new char[10];    std::strcpy(info1.p, "haha");    //info2.p = nullptr;//C++的空指针    info2.p = new char[100];    std::strcpy(info2.p, "hehe");    info1.set(89);    info2.set(98);    swap(info1, info2);    std::cout << info1.name << "   "<< info1.data  <<"   "<<info1.get()<< std::endl;    std::cout << info1.p << std::endl;    std::cout << info2.name << "   "<<info2.data  <<"    "<<info2.get()<< std::endl;    std::cout << info2.p << std::endl;    std::cin.get();}
0 0
原创粉丝点击