//类模版中的static关键字
#include<iostream>
using namespace std;

/*
类模板本质上是c++编译器根据类型参数创建了不同的类,
c++编译器在利用类模板生成类的时候会为每个类生成一个static变量
那么对于类中的static关键字就非常好理解了
static关键字修饰的变量是属于类的 同一个类的对象共享类的static静态变量

类模板中的static修饰的变量数据类型必须是确定的 不可以是类型参数  因为静态变量在类对象之前初始化
这时候还没有通过类模板生成类类
*/

template<typename T>
class Point{
public:
    Point(T a,T b){
        this->x = a;
        this->y = b;
    }
    static int total;
    static void Print(){
        cout << "total=" << total << endl;
    }
private:
    T x;
    T y;
};

//类中静态变量唯一的初始化方式
template<typename T>
int Point<T>::total = 10;

void ProtectA(){
    Point<int> p1(3,3);
    p1.total = 12;
    Point<int> p2(5, 5);
    Point<float> p3(4.0, 4.0);
    p3.total = 13;
    //同一个类共享一个静态变量
    p2.Print();
    //不同的类不会共享一个静态变量
    Point<float>::Print();
}

void main(){
    ProtectA();
    system("pause");
}

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-22
  • 2021-12-11
  • 2021-10-29
  • 2021-12-13
猜你喜欢
  • 2021-12-14
  • 2021-10-10
  • 2021-09-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-12
相关资源
相似解决方案