c++ 类中 静态变量和静态函数

#include <iostream>
using namespace std;

 

class Static{
public:
        Static(int, int, int);
        ~Static(){}
        int Getsum();
private:
        int x;
        int y;
        int z;
        static int sum;
};


int Static::sum = 0;
Static::Static(int newx, int newy, int newz)
{
       x = newx;
       y = newy;
       z = newz;
       //如果在这里计算sum的值时,而在Getsum()函数中只是返回sum的值,则在执行完构造函数a(1,1,1)是sum值为3
       //接着执行构造函数b(2,2,2),这以后sum的值变为6,static型的,所有的sum都为6
       //sum = x + y + z;
}
int Static::Getsum()
{
      sum = x + y + z;
      //在执行a.Getsum()时,sum = 3;返回值为3;然后又执行b.Getsum(),sum = 6,返回值为6;
      //对象a中的sum也变为了6,但是a.Getsum()的返回值不变
      return sum;
}

//****************************************
class M
{
public:
        M(int a);
        static void f1(M m); //静态函数有一个类参数
private:
        int A;
        static int B;
};

 

M::M(int a)
{
        A = a;
        B += a;
}
void M::f1(M m)
{
        cout << "A = " << m.A << endl; //调用类中的非静态成员要用通过对象调用
        cout << "B = " << B << endl;
}
int M::B = 0;
//*****************************************
int main()
{
      Static a(1,1,1),b(2,2,2);   //只执行了Static类的构造函数,子函数Getsum()并未执行
      cout << a.Getsum() << endl; //执行了a的Getsum()函数,返回值输出返回值,而不是最后的static型的sum的值
      cout << b.Getsum() << endl; //执行了b的Getsum()函数,返回值输出返回值,而不是最后的static型的sum的值
      cout << a.Getsum() << endl; //输出的是a.Getsum()的返回值,而不是sum的值

      M::f1(x1);    //调用静态函数时不能用对象调用,因为静态函数不属于某一个对象
      M::f1(x2);    //它是属于类的,不能用对象调用,只能用类调用

 

      return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值