我们刚学派生类,小类编了以下一个作业程序,但不能运行,不知有哪位能给小弟指出错误:
#include<iostream.h>
class fruit
{
private:char fruitcolour,fruitsize;float fruitprice;
public:fruit(char fc,char fs,float fp)
{fruitcolour=fc;fruitsize=fs;fruitprice=fp;}
};
class trees
{
private:char leafcolour;char leafsize;float averageheight;
public:trees(char lc,char ls,float ah)
{leafcolour=lc;leafsize=ls;averageheight=ah;}
};
class apple:public fruit,public trees
{
public:apple(char fco,char fsi,float fpr,char lco,char lsi,float ahi):fruit(fco,fsi,fpr),trees(lco,lsi,ahi){}
};
void main()
{
apple (red,big,5.00,green,thick,2.00);
cout<<"the apples's colour is "<<apple::fruitcolour;
}
(我用水果和树两个类派生出萍果这个类,其中错误的地方请大家指出!谢谢!)
这个程序有五个错误,分为两类:一类是在参数类型与形参类型不符:apple类的构造函数public:apple(char fco,char fsi,float fpr,char lco,char lsi,float ahi)的第1、2、4、5个参数是char,而在main()函数中你给出的是 red, big, green, thick,系统认为它们是变量名,而又找不到它们的定义,所以出错;第二类是在cout<<"the apples's colour is "<<apple::fruitcolour中,第一用类名直接访问的只有静态属性,非静态属性只能用对象名访问,但对象能访问的非静态属性只有公有属性,所以应该把fruitcolour改成公有属性。修改结果有以下两种:
1
#include<iostream.h>
class fruit
{
private:char fruitsize;float fruitprice;
public:char fruitcolour;
fruit(char fc,char fs,float fp)
{fruitcolour=fc;fruitsize=fs;fruitprice=fp;}
};
class trees
{
private:char leafcolour;char leafsize;float averageheight;
public:trees(char lc,char ls,float ah)
{leafcolour=lc;leafsize=ls;averageheight=ah;}
};
class apple:public fruit,public trees
{
public:apple(char fco,char fsi,float fpr,char lco,char lsi,float ahi):fruit(fco,fsi,fpr),trees(lco,lsi,ahi){}
};
void main()
{
apple aa('r','b',5.00,'g','t',2.00);
cout<<"the apples's colour is "<<aa.fruitcolour;
}
2
#include<iostream.h>
#include <string.h>
class fruit
{
private:char fruitsize[10];float fruitprice;
public:char fruitcolour[10];
fruit(char *fc,char *fs,float fp)
{strcpy(fruitcolour,fc);strcpy(fruitsize,fs);fruitprice=fp;}
};
class trees
{
private:char leafcolour[10];char leafsize[10];float averageheight;
public:trees(char *lc,char *ls,float ah)
{strcpy(leafcolour,lc);strcpy(leafsize,ls);averageheight=ah;}
};
class apple:public fruit,public trees
{
public:apple(char *fco,char *fsi,float fpr,char *lco,char *lsi,float ahi):fruit(fco,fsi,fpr),trees(lco,lsi,ahi){}
};
void main()
{
apple aa("red","big",5.00,"green","thick",2.00);
cout<<"the apples's colour is "<<aa.fruitcolour;
}