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

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日

    悬赏问题

    • ¥80 关于海信电视聚好看安装应用的问题
    • ¥15 vue引入sdk后的回调问题
    • ¥15 求一个智能家居控制的代码
    • ¥15 ad软件 pcb布线pcb规则约束编辑器where the object matpcb布线pcb规则约束编辑器where the object matchs怎么没有+15v只有no net
    • ¥15 虚拟机vmnet8 nat模式可以ping通主机,主机也能ping通虚拟机,但是vmnet8一直未识别怎么解决,其次诊断结果就是默认网关不可用
    • ¥20 求各位能用我能理解的话回答超级简单的一些问题
    • ¥15 yolov5双目识别输出坐标代码报错
    • ¥15 这个代码有什么语法错误
    • ¥15 给予STM32按键中断与串口通信
    • ¥15 使用QT实现can通信