1 #include <iostream> 2 using namespace std; 3 4 class Values 5 { 6 private: 7 8 //类里的 9 const int cSize; //常量成员的初始化,必须在构造函数中进行,每个对象都有,只是成员常量数据在初始化就不能改变 10 11 12 //禁止在类内对"非const的静态成员"进行初始化 13 //static int sFloat = 100; //Values.cpp:8:24: error: ISO C++ forbids in-class initialization of non-const static member ‘Values::sFloat’ 14 static float sFloat; //类的静态成员,所以对象共享同一块内存单元 15 static int sInts[]; 16 17 18 19 static const float scFloat; //类的静态常量成员在类中初始化 20 static const int scInts[]; 21 22 int size; 23 24 public: 25 Values(const int cSize, int sz) : cSize(cSize), size(sz) {} 26 27 void print() const; 28 29 static void printStatic(); 30 }; 31 32 33 //类的普通private成员 34 //int Values::size = 100; //error C2350: ‘Values::size‘ is not a static member 35 36 //类的静态数据成员初始化 37 float Values::sFloat = 1.1; 38 int Values::sInts[] = {1, 2, 3}; 39 40 //类静态常量数据成员初始化 41 const float Values::scFloat = 100.01; 42 const int Values::scInts[] = {11, 22, 33}; 43 44 //定义一个全局变量size 45 int size = 7; 46 47 //成员函数中,可以访问到类的静态成员 48 void Values::print() const 49 { 50 cout<<"::size = "<<size<<endl; 51 cout<<"Values::cSize = "<<cSize<<endl; 52 cout<<"Values::size = "<<size<<endl; 53 cout<<"Values::sFloat = "<<sFloat<<endl; 54 cout<<"Values::scFloat = "<<scFloat<<endl; 55 } 56 57 //在静态成员函数中,只能访问到类的静态成员 58 void Values::printStatic() 59 { 60 cout<<"printStatic(), Values::scFloat = "<<scFloat<<endl; 61 cout<<"printStatic(), Values::scInts[] = {"<< scInts[0] <<", " <<scInts[1] << ", " << scInts[2] <<"}"<<endl; 62 63 cout<<"printStatic(), Values::sFloat = "<<sFloat<<endl; 64 cout<<"printStatic(), Values::sInts[] = {"<< sInts[0] <<", " <<sInts[1] << ", " << sInts[2] <<"}"<<endl; 65 } 66 67 68 int main() 69 { 70 Values v(1, 3); 71 72 v.print(); 73 74 Values::printStatic(); 75 76 return 0; 77 } 输出:
::size = 3
Values::cSize = 1
Values::size = 3
Values::sFloat = 1.1
Values::scFloat = 100.01
printStatic(), Values::scFloat = 100.01
printStatic(), Values::scInts[] = {11, 22, 33}
printStatic(), Values::sFloat = 1.1
printStatic(), Values::sInts[] = {1, 2, 3}
时间: 2024-11-09 06:05:58