#include <iostream>
#include <vector>
using std::vector;
using namespace std;
#include <iostream>
#include <vector>
using namespace std;
class Test
{
public:
static int count;
};
int Test::count(0); /*static类对象必须在类外进行初始化:static修饰的变量先于对象存在,所以static修饰的变量要在类外进行初始化*/
/*static修饰的成员变量在对象中是不占用内存的,因为它不是跟对象一起在堆或者栈中生成的,它是在静态存储区生成的*/
int main1()
{
Test t1;
cout << t1.count << endl;
Test t2;
t1.count = 100; /*static修饰的类变量是所有对象共享的,只要有一个对象改变了static静态变量,整个对象的都会变*/
cout << t2.count << endl;
system("pause");
}
/*************static修饰类成员函数***************************/
class Text
{
public:
static int fun() {
/*return num; */
return count; /*由于static修饰的类成员属于类不属于对象,因此static类成员函数是没有this指针的,this指针是
指向本对象的指针。正因为没有this指针,所以static类成员函数不能访问非static的类成员,只能访问
static修饰的类成员*/
}
static int count;
int num;
};
int main()
{
system("pause");
}
c++的static修饰类成员和类函数
猜你喜欢
转载自blog.csdn.net/zhizhengguan/article/details/81183602
今日推荐
周排行