c++学习

1.再谈结构体

c++中除支持结构体之外,还支持类class(这是啥我也不知道以后用得到在学)。c++不需要用typedef的方式定义一个struct,例如下面的代码。
c的代码

#include<stdio.h>

struct mama
{
    int a;
};
int main()
{
    struct mama x;
    scanf("%d",&x.a);
    printf("%d\n",x.a);
    return 0;
}

c++的代码

#include<iostream>
using namespace std;
struct mama
{
    int a;
};
int main()
{
    mama x;
    cin>>x.a;
    cout<<x.a<<endl;
    return 0;
}

而且c++中的struct里除了可以有变量(称为成员变量)之外还可以有函数(称为成员函数)。
例子又来了【这里用到了重载操作符】(不会用,先理解一下意思)

#include<iostream>
using namespace std;
struct Point
{
    int x,y; //成员变量
    Point (int x=0,int y=0):x(x),y(y){}/*成员函数。当不给x,y赋值时为0。可以这样使用 Point b(1,2); 即b.x=1,b.y=2;*/ 

};
Point operator + (const Point &A,const Point & B){
    return Point (A.x+B.x,A.y+B.y); //重新定义+ 此时的+: a+b  是a.x+b.x , a.y+b.y;
}
ostream& operator << (ostream &out,const Point& p){
    out<<"("<<p.x<<","<<p.y<<")"; //重新定义流输出 输出这样的东西(a.x+b.x , a.y+b.y)
    return out;
}
int main()
{
    Point a,b;
    cin>>a.x>>a.y>>b.x>>b.y;
    cout<<a+b<<"\n";
    return 0;
}

在结构体中定义的函数叫构造函数(ctor)。构造函数是在声明变量的时候用的像上面的这个

Point (int x=0,int y=0):x(x),y(y){}  //是为了赋值更方便直接b(1,2);就行。

也可以改成

Point(int x=0,int y=0){this->x=x; this->y=y;} //this是指向当前对象的指针。this->x的意思是当前对象成员变量x即  (*this).x;

提示

  1. c++中函数中结构体可以有一个或多个构造函数,在声明变量时调用。
  2. c++中的函数(不只是构造函数)参数可以拥有默认值。

先这样以后补充。

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐