我在这里浏览了与静态成员变量相关的所有线程,但不幸的是,这无法帮助我找出原因。
这就是问题:
1) 定义一个类名 DVD_DB。包括以下成员。
DATA MEMBERS:
Name of DVD – private character array, size 10
Price – private double variable
Quantity – private int variable
A private static int variable to keep track of how many DVD have been created so far.
MEMBER FUNCTIONS:
To assign initial values
To set price and quantity
To get price and quantity
To Print DVD
To display how many DVD has been created so far.
在主要功能中使用一个 DVD 阵列并演示一个 DVD 商店。即用户可以选择 DVD 并购买它,当 DVD 售出时,数量会下降。
而且,我已经编写了这段代码来解决它。但是在构建此代码时遇到问题。编译器对我使用静态变量 cnt 的所有地方都说未定义的引用。还有一个问题,因为我最初想将 cnt 设置为 0,由于它是私有变量,该怎么做?
可以做些什么来解决未定义的参考问题?
class dvd_db{
private:
string name;
float price;
int quantity;
static int cnt;
public:
dvd_db()
{
name="";
price=0;
quantity=0;
cnt++; //to count the total number of dvds
}
dvd_db(string str,float p,int q)
{
name = str;
price = p;
quantity = q;
// cnt=0;
cnt+=q;
}
void set_name(string str)
{
name = str;
}
string get_name(void)
{
return name;
}
void set_price(float p)
{
price = p;
}
float get_price(void)
{
return price;
}
void set_quantity(int q)
{
quantity = q;
cnt+=q;
}
int get_quantity(void)
{
return quantity;
}
void show_info(void)
{
cout<<"Name if the DVD: "<<name<<endl;
cout<<"Price: "<<price<<endl;
cout<<"Available Quantity: "<<quantity<<endl;
}
void total(void)
{
cout<<"Total number of dvd is: "<<cnt<<endl;
}
void buy(void)
{
if(quantity>0){
quantity--;
cnt--;
cout<<"Thanks for purchasing this item"<<endl;
}
else
cout<<"This Item can not be bought."<<endl;
}
};
//dvd_db::cnt=0;
int main()
{
dvd_db dvd[3];
int i,j,k,n;
dvd[0].set_name("A Beautiful Mind");
dvd[0].set_price(50.00);
dvd[0].set_quantity(10);
dvd[1].set_name("October Sky");
dvd[1].set_price(50.00);
dvd[1].set_quantity(15);
dvd[2].set_name("Shawshank Redemption");
dvd[2].set_price(50.00);
dvd[2].set_quantity(100);
cout<<"Welcome to Banani International Movie House"<<endl;
cout<<"Enter the serial no. to buy an item, -1 to view total no. of dvd(s), or enter 0 to quit."<<endl;
cout<<"Here is our collection:"<<endl<<endl<<endl<<endl;
for(i=0; i<3; i++){
cout<<"serial no. "<<i+1<<endl;
cout<<"------------------------------------"<<endl;
dvd[i].show_info();
}
cout<<"Enter: "<<endl;
while(cin>>n)
{
if(n==-1){
dvd[0].total();
cout<<"Enter: "<<endl;
continue;
}
dvd[n-1].buy();
cout<<"Enter: "<<endl;
}
return 0;
}