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

C++知识点案例 笔记-5

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

C++知识点案例 笔记-5

1.关系运算符重载
2.类型转换函数重载
3.转换构造函数
4.函数模板
5.显式实例化
6.类模板外定义模板函数

1.关系运算符重载

==关系运算符重载==

//直接(按分数)比较两个对象
#include
using namespace std;
class Student
{

public:
    friend ostream& operator<< (ostream& os,const Student& st);
    friend istream& operator>> (istream& is, Student& st);

    friend bool operator == (const Student& st1,const Student& st2);
    friend bool operator != (const Student& st1,const Student& st2);
    friend bool operator >  (const Student& st1,const Student& st2);
    friend bool operator <  (const Student& st1,const Student& st2);
private:
    int id;
    double  score;

};
ostream& operator<< (ostream& os,const Student& st)
{
    os <<"id:"<> (istream& is,Student& st)
{
    is >> st.id >> st.score;
    return is;
}

bool operator == (const Student& st1,const Student& st2)
{
    return st1.score == st2.score;
}
bool operator != (const Student& st1,const Student& st2)
{
    return !(st1.score == st2.score);
}
bool operator > (const Student& st1,const Student& st2)
{
    return (st1.score > st2.score);
}
bool operator < (const Student& st1,const Student& st2)
{
    return (st1.score < st1.score);
}
int main()
{
    Student st1,st2;
    cout<<"请输入两名学生的ID和score:"<>st1>>st2;
    if (st1 > st2)
    {
        cout<<"st1分数高于st2"< 
 

2.类型转换函数重载

==类型转换函数重载==



#include
using namespace std;
class bian
{
private:
    int m,n;
public:
    bian(int m1,int n1):m(m1),n(n1){}
    void show()
    {
        cout<<"bb:"<(m);
    }
};
int main()
{
    bian bb(69,96);
    bb.show();
    char ch = bb;
    cout< 
 

3.转换构造函数

==转换构造函数==


#include
using namespace std;
class jie
{
private:
    int m,n;
public:
    jie(int a, int b):m(a),n(b){}
    jie(double c)
    {
        cout<<"把m转换成字符型,并给n一个值"<(c);
        n = 0;
    }
    void show()
    {
        cout< 
 

4.函数模板

==函数模板==
//目的 函数运行与类型无关
#include
using namespace std;
template
T add(T x,T y)
{
    return x+y;
}
int main()
{
    cout<

5.显式实例化

==显式实例化==
//指定参数类型,便于不同类型数据类型相加
#include
using namespace std;
template
T add(T x,T y)
{
    return x+y;
}
template int add(int x,int y);
int main()
{
    cout<(3.1415,'a')< 
 

6.类模板外定义模板函数

==类模板外定义模板函数==
#include
using namespace std;
template
class Fly
{
private:

    int size;
    T* str;
public:
    Fly(T fly[],int s);
    void show();
};
//类模板外定义成员函数
template
Fly::Fly(T fly[],int s)
{
    str = new T[s];
    size = s ;
    for(int i = 0;i < size; i++)
    {
        str[i] = fly[i];
    }
}
template
void Fly::show()
{
    for(int k = 0; k  F1(ffly,5);
    F1.show();

    int jfly[]={5,2,1,1314};
    //创建类模板对象
    Fly F2(jfly,4);
    F2.show();

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

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

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