删之前
#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;
}
希望解答详细一点,明明有自动开辟空间呀,谢谢了
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未定义,也就是还没有分配内存,显然是不可以访问的。