c++中类的静态成员变量以及静态成员函数

静态成员

类内声明,类外初始化,所有对象访问同一个变量,可通过类名访问,也可通过对象访问

#include <iostream>

using namespace std;

class dev{
  
  public:
    static int cay;

};

int dev::cay = 100;

int main(){
  dev a;
  cout << "对象访问: " << a.cay << endl;
  cout << "类名访问" << dev::cay << endl;
  dev b;
  b.cay = 1000;
  cout << "对象访问: " << a.cay << endl;
}

在这里插入图片描述

静态成员函数只能访问静态成员变量,不能访问非静态变量

#include <iostream>

using namespace std;

class dev{
  
  public:
    static int cay;

    static void test(){
      cay = 10086;
      cout << "test" << endl;
    }

};

int dev::cay = 100;

int main(){
  dev a;
  a.test();
  dev:: test();
}

在这里插入图片描述
类指针

#include <iostream>

using namespace std;

class dev{
  
  public:
    static int cay;

    static void test(){
      cay = 10086;
      cout << "test" << endl;
    }

    dev* returndev(){
      this->cay += 1;
      return this;
    }

};

int dev::cay = 100;

int main(){
   dev a;

   dev* b = a.returndev();
   cout << b->cay << endl;
}

返回一个指针

返回当前对象本身

#include <iostream>

using namespace std;

class dev{
  
  public:
    static int cay;

    static void test(){
      cay = 10086;
      cout << "test" << endl;
    }

    dev& returndev(){
      this->cay += 1;
      return *this;
    }

};

int dev::cay = 100;

int main(){
   dev a;

   dev b = a.returndev();
   cout << b.cay << endl;
}

返回一个副本

#include <iostream>

using namespace std;

class dev{
  
  public:
    static int cay;

    static void test(){
      cay = 10086;
      cout << "test" << endl;
    }

    dev returndev(){
      this->cay += 1;
      return *this;
    }

};

int dev::cay = 100;

int main(){
   dev a;

   dev b = a.returndev();
   cout << b.cay << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值