开发者社区> 问答> 正文

java中静态成员函数如何举例?

已解决

java中静态成员函数如何举例?

展开
收起
游客gzyuldo4mrg6i 2022-04-02 22:57:14 702 0
1 条回答
写回答
取消 提交回答
  • 推荐回答

    #include

    using namespace std;

    class Myclass

    {

    public : 
    
        Myclass(int a, int b, int c);
    
        static void GetSum(); // 声明静态成员函数
    
    private :
    
        int a, b, c;
    
        static int Sum; //声明静态数据成员
    

    };

    int Myclass::Sum=0; //定义并初始化静态数据成员

    Myclass::Myclass(int a, int b, int c)

    {

    this->a = a;
    
    this->b = b;
    
    this->c = c;
    
    Sum += a + b + c; //非静态成员函数可以访问静态数据成员
    

    }

    void Myclass::GetSum() //静态成员函数的实现

    {

    // cout<<a<<endl; //错误代码,a是非静态数据成员
    
    cout<<"Sum="<<Sum<<endl;
    

    }

    int main()

    {

    Myclass M(1, 2, 3);
    
    M.GetSum();
    
    Myclass N(4, 5, 6);
    
    N.GetSum();
    
    Myclass::GetSum();
    

    }

    2022-04-02 23:01:31
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载