//静态成员变量优点:实现各对象的数据共享,比全局变量更加安全
//静态成员函数作用:为了更好地使用、处理静态成员变量,一般不用(也可以用:需要加对象名)来引用非静态成员
# include <iostream>
using namespace std;
class Box
{
public:
Box(){};
Box(int, int);
int Volume();
static void set_height(int); //声明静态成员函数用于修改静态成员变量height
static void set_length(Box &, int); //怎么使用静态成员函数修改非静态成员变量呢?
private: //此时该类中静态成员变量只能通过静态成员函数修改(测试1需要去掉private)
static int height; //静态数据成员在定义此类时会被单独分配到一处空间(静态存储空间)
int width;
int length;
};
int Box::height = 10; //正确:静态成员变量初始化
int main()
{
/* //测试1:关于静态成员变量的使用
Box B1, B2;
Box::height = 12; //非private静态成员变量可以直接通过类名引用进行修改
B1.height = 13; //非private静态成员变量也可以直接通过对象引用进行修改,修改后其他对象引用该变量也变成13
cout << "B1.height = " << B1.height << endl; //静态成员变量为该类的对象所共有,既可以通过对象引用,亦可通过类名引用
cout << "Box::height = " << Box::height << endl; //效果同上
cout << "B2.height = " << B2.height << endl;
*/
//测试2:关于静态成员函数的使用
Box B3(10,10);
cout << "此时B3的体积为:" << B3.Volume() << endl;
B3.set_height(15);
cout << "修改后B3的体积为:" << B3.Volume() << endl;
B3.set_length(B3, 20);
cout << "再次修改后B3的体积为:" << B3.Volume() << endl;
return 0;
}
Box::Box(int w, int l)
{
width = w;
length = l;
//int Box::height = 10; //error:静态成员变量不能再构造函数中初始化
}
int Box::Volume()
{
return width * length * height;
}
void Box::set_height(int h) //定义时无需加static
{
height = h; //此时无需加作用域
}
void Box::set_length(Box &B, int l) //试图使用静态成员函数修改非静态的值, 需要传入对象且为引用或者指针型形参变量
{
B.length = l; //
}
C++中的static问题
最新推荐文章于 2023-03-27 09:29:19 发布