计算机魔术师 2022-03-25 21:22 采纳率: 100%
浏览 39
已结题

c++为什么定义了静态成员数据不赋值会报错?不是默认为0吗

img

删之前

img


源代码:

#include<iostream>
using namespace std;


class sell
{
    public:
        sell(int n, int m, float y):num(n),quantity(m),price(y){
        };
        static float average();
        static void total(const sell *p);
        static float discount;
        static int sum;
    private:
        int num;
        int quantity;
        float price;
        
        static int s_n;
        static float averages;
        
};

int sell::sum = 0;
int sell::s_n = 0;
float sell::averages = 0;
float sell::discount = 0.9;

//void sell::total()
//{
//    sum+=quantity*discount*price; //这里quantity不是静态成员,静态函数没有*this指针无法找到quantity 
//    s_n+=quantity;
//}

void sell::total(const sell *p)
{
    sum+=(*p).quantity*(*p).discount*(*p).price; 
    s_n+=(*p).quantity;
}

float sell::average()
{
    return(sum/s_n);
}

int main()
{
    const sell staff[3] = {
        sell(101, 5, 23.5),
        sell(101, 5, 23.5),
        sell(101, 5, 23.5),
    };
    
    for(int i = 0;i < 3;i++)
    {
        sell::total(&staff[i]);
    }
    
    cout << "The sum is " << sell::sum <<endl<<" The average is " <<sell::average() << endl;
    
    return 0;
}

希望解答详细一点,明明有自动开辟空间呀,谢谢了

  • 写回答

1条回答 默认 最新

  • bostonAlen 2022-03-26 11:07
    关注
    class A { 
        public: 
            static int a; //声明但未定义
     }; 
    int A::a = 3; //定义了静态成员变量,同时初始化。也可以写"int A:a;",即不给初值,同样可以通过编译
    
    

    静态成员变量在类中仅仅是声明,没有定义,所以要在类的外面定义,实际上是给静态成员变量分配内存。

    
    //test.cpp 
    #include <stdio.h> 
    class A { 
        public: 
            static int a; //声明但未定义
     }; 
    int main() { 
        printf("%d", A::a);
        return 0;
    }
    
    

    编译以上代码会出现“对‘A::a’未定义的引用”错误。这是因为静态成员变量a未定义,也就是还没有分配内存,显然是不可以访问的。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 4月3日
  • 已采纳回答 3月26日
  • 创建了问题 3月25日

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改