[语法糖自检] cpp class 速成

class 的用法和结构体差不多。

class test{
  public:
    int a;
}

成员有publicprotectedprivate三种。

可以在里面写函数:

class test{
  public:
    int a;
    int readb(){
      return b;
    }
    void writeb(int num){
      b=num;
      return;
    }
  private:
    int b;
};
test n;

int main(){
  
  n.a=1; //ok
  cout<<n.a<<endl;
  
  n.b=1; //error
  cout<<n.b<<endl;
  
  n.writeb(1); //ok
  cout<<n.readb()<<endl;
  
}

重载运算符:

class test{
  public:
    int a,b;
    int operator+(const test& other){
      return a+other.a;
    }
    int operator-(const test& other){
      return b-other.b;
    }
};
test n1,n2;

int main(){
  
  n1.a=2;
  n1.b=3;
  
  n2.a=2;
  n2.b=1;
  
  cout<<n1+n2<<endl; //2+2=4
  cout<<n1-n2<<endl; //3-1=2
  
}

使用构造函数设置默认值:

class test{
  public:
    int a,b;
    test(int _a=1,int _b=2){
      a=_a;
      b=_b;
    }
};
test n(3,4);
test m;

int main(){
  
  cout<<n.a<<endl; //3
  cout<<n.b<<endl; //4
  
  cout<<m.a<<endl; //1
  cout<<m.b<<endl; //2

}