c++:第一课

    xiaoxiao2025-09-05  28

    c++头文件格式:

    #include<fstream> --------->文件头文件 #include<algorithm>----------->算法头文件

    #include<iostream> using namespace std;//namespace是命名空间,std中包含封装好的函数,例如cout //假如不写namespace std,在使用cout时,格式变更为std::cout; //自己在规定namespace时,使用的时候,尽量将函数写在namespace的大空间,也就是大括号内。 class inta{ public://公开区,需要权限最小,都可以访问 int a; void setB(int bb){b=bb;} int getB(void){return b;} void setC(int cc){c=cc;} int getC(void){return c;} protected://保护区,允许inta的子类进行访问,外部函数不准访问 int b; private://私有区,只允许自己访问 int c; }; int main(){ inta r; r.a=10; r.b=setB(20); r.c=setC(30); cout<<r.a<<endl<<getB<<endl<<getC<<endl; }

    构造函数

    void setB(int bb){b=bb;} int getB(void){return b;} void setC(int cc){c=cc;} int getC(void){return c;}

    析构函数

    ## 暂时不懂

    函数重载

    //定义三个函数名一样的函数,参数不同 //主函数在引用函数时,是根据参数的不同自主判断该引用的函数 #include <iostream> #include <fstream> using namespace std; void fun(int t) { cout << "t = " << t << endl; cout << "int" << endl; } void fun(int ,double){ cout << "int double" << endl; } #include <string> void fun(string){ cout << "string" << endl; } void fun(double d){ cout << "double"<< endl; } int main(){ fun(1,2.3); fun("NBA"); fun(3.4); return 0; }

    C++支持函数重载,C不支持(也就是所谓的函数名一样)

    引用

    #include<stdio.h> #include<stdlib.h> void turn(int &x, int &y)//有引用,交换值有效(即引用就是函数的别名) { int t; t = x; x = y; y = t; } int main() { int a, b; scanf_s("%d%d", &a, &b); turn(a, b); printf("%d %d\n",a,b); system("pause"); return 0; }

    https://blog.csdn.net/dujiangyan101/article/details/2844138 指针和引用的异同详见上方链接 在使用函数的时候,参数直接写,不用更改

    运算符重载

    #include<iostream> #include<algorithm> using namespace std; namespace arc{//定义一个arc的命名空间 struct rect{ public: rect(int w=1,int l=1){ width=w; len=l; } double area(void){ return width*len; } double lenth(); private: double width; double len; }; double rect::lenth(){ return 2*(width+len); } bool operator<(rect r,rect l){//运算符重载,格式《(函数类型) operator (要重载的)(参数)》 return r.area()<l.area(); } bool operator>(rect r,rect l){ return r.lenth()>r.lenth(); } } int main(){ using namespace arc; rect r[5]={rect(10,100),rect(10,20),rect(200,20),rect(30,40),rect(30,50)}; // cout <<"area="<<r.area()<<endl; // cout <<"lenth="<<r.lenth()<<endl // sort(r,r+5); cout<<"sort="; for(int i=0;i<5;i++) cout<<r[i].area()<<endl; sort(r,r+5,std::greater<rect>()); cout<<"lenth="; for(int i=0;i<5;i++) cout<<r[i].lenth()<<endl; return 0; }
    最新回复(0)