Static基本用法总结

来源:互联网 发布:乐清知临中学地址 编辑:程序博客网 时间:2024/06/07 00:15
#include <iostream>
using namespace std;


class test
{
private:
int x,y;


public:
static int num;
static int sum;
      //static int sum=3;  错误:ISO C++ 不允许在类内初始化非常量静态成员‘sum’
      /*静态成员不可在类体类进行赋值,因为它是被所有该类的对象所共享的。你在一个对象里
        给它赋值没其他对象的该成员也会发生变化,为了避免混乱,所以不可在类体类进行赋值*/


// test(int x,int y);

static int getNum();
void getSum();


};


//静态成员的值对所有对象是一样的,静态成员只能在类外初始化
int test::num=120;


int test::getNum()
{
return num;
}


int test::sum=0;
/*
test::test(int x,int y)
{
this->x = x;
this->y = y;


sum+= x+y;
}
*/
void test::getSum()
{
num=getNum()+20;
cout<<"sum="<<sum<<endl;
cout<<"num="<<num<<endl;
}




int main()
{

/**************************************************************************************************************************/

/*
int test::num=120;


int test::getNum()
{
      //return this->num;  //错误:静态成员函数中不能使用‘this’
                // 静态成员函数没有this指针
return  num;
}


总结: 静态成员和静态成员函数两种访问方式
            <1>  类名::静态成员或静态成员函数
    <2>  对象::静态成员或静态成员函数


cout<<test::getNum()<<endl;   
cout<<test::num<<endl;


test t;
cout<<t.getNum()<<endl;
cout<<t.num<<endl;
      //cout<<t::num<<endl;        错误:‘t’is not a class or namespace
      //cout<<t::getNum()<<endl;  错误:‘t’is not a class or namespace
 
显示结果:
120
120
120
120
*/
/*********************************************************************************************************************/
/*
int test::num=120;


int test::getNum()
{
   // i=100;  //错误:‘i’在此作用域中尚未声明  静态成员函数不能调用非静态成员变量
num=num+20;;
return  num;
}
总结:静态成员函数可以改变静态成员变量的值,即静态成员函数可以调用静态成员变量,
          而静态成员函数不能直接调用非静态成员变量的值,也不能访问非静态成员函数。


cout<<test::num<<endl;
cout<<test::getNum()<<endl;

test t;
cout<<t.num<<endl;
cout<<t.getNum()<<endl;
cout<<t.num<<endl;
显示结果:
120
140
140
160
160
*/
/********************************************************************************************************************/
/*
int test::sum=0;


test::test(int x,int y)
{
this->x = x;
this->y = y;


sum+= x+y;
}


void test::getSum()
{
num=getNum()+20;
cout<<"sum="<<sum<<endl;
cout<<"num="<<num<<endl;
}
总结:非静态成员函数可以任意的访问静态成员变量和静态成员函数,
           但是访问一次,改变了静态成员变量的值后,静态成员的值是永久变的。


test t(5,6);
t.getSum();

test t2(1,4);
t2.getSum();
       //test::getSum();   错误:没有对象无法调用成员函数‘void test::getSum()’

显示结果:
sum=11
num=140
sum=16
num=160


*/
/****************************************************************************************************************/
/*
class test
{
private:
int x,y;


public:
static int num;
static int sum;


static int getNum();
void getSum();


};

总结:静态成员是类所有的对象的共享成员,而不是某个对象的成员,它在对象中不占用存储空间,

          这个属性为整个类所共有,不属于任何一个具体的对象



test t;
cout<<sizeof t<<endl;
      //cout<<sizeof test<<endl;  错误:无法求类占多少字节


显示结果:
8
//故一个对象的占两个int, 8个字节
*/
/*************************************************************************************/
return 0;
}
原创粉丝点击