![]() |
#2
rjsp2016-09-02 15:33
|

//Furniture.h
#include <iostream>
#include <string>
using namespace std;
class Furniture //家具类
{
private:
string type; //家具类型
string mat; //家具主材料
double price; //家具价格
public:
Furniture(string type,string mat,double price):mat(mat),price(price){}
string getMaterial()
{
return mat;
}
double getprice()
{
return price;
}
string getType()
{
return type;
}
};
class Sofa:public Furniture //沙发类
{
private:
int seats;
public:
Sofa(string mat,double price,int seats):Furniture("沙发",mat,price),seats(seats){}
int getseats()
{
return seats;
}
};
class Bed:public Furniture //床 类
{
private:
string bedtype;
public:
Bed(string mat,double price,string bedtype):Furniture("床",mat,price),bedtype(bedtype){}
string getBedType()
{
return bedtype;
}
};
void show(Furniture *f)
{
cout<<"家具类型:"<<f->getType()<<" 主材料:"<<f->getMaterial()<<" 价格:"<<f->getprice()<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"向上转型机制示例:"<<endl;
Sofa sofa1("木材",870.00,3);
Bed bed1("木材",1280.00,"双人");
Furniture *sofa2=new Sofa("钢材",410.00,1); //用派生类指针初始化基类指针
Furniture &bed2=*new Bed("竹子",1280.00,"单人"); //用派生类对象初始化基类的引用
Furniture bed3=bed1; //派生类对象赋值给基类对象
show(&sofa1);
show(sofa2);
show(&bed3);
show(&bed2);
delete sofa2; //释放动态空间
delete &bed2; //释放动态空间
return 0;
}
#include <iostream>
#include <string>
using namespace std;
class Furniture //家具类
{
private:
string type; //家具类型
string mat; //家具主材料
double price; //家具价格
public:
Furniture(string type,string mat,double price):mat(mat),price(price){}
string getMaterial()
{
return mat;
}
double getprice()
{
return price;
}
string getType()
{
return type;
}
};
class Sofa:public Furniture //沙发类
{
private:
int seats;
public:
Sofa(string mat,double price,int seats):Furniture("沙发",mat,price),seats(seats){}
int getseats()
{
return seats;
}
};
class Bed:public Furniture //床 类
{
private:
string bedtype;
public:
Bed(string mat,double price,string bedtype):Furniture("床",mat,price),bedtype(bedtype){}
string getBedType()
{
return bedtype;
}
};
void show(Furniture *f)
{
cout<<"家具类型:"<<f->getType()<<" 主材料:"<<f->getMaterial()<<" 价格:"<<f->getprice()<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"向上转型机制示例:"<<endl;
Sofa sofa1("木材",870.00,3);
Bed bed1("木材",1280.00,"双人");
Furniture *sofa2=new Sofa("钢材",410.00,1); //用派生类指针初始化基类指针
Furniture &bed2=*new Bed("竹子",1280.00,"单人"); //用派生类对象初始化基类的引用
Furniture bed3=bed1; //派生类对象赋值给基类对象
show(&sofa1);
show(sofa2);
show(&bed3);
show(&bed2);
delete sofa2; //释放动态空间
delete &bed2; //释放动态空间
return 0;
}
问题描述,本来输出的结果应该是:
家具类型:沙发 主材料:木材 价格:870
家具类型:沙发 主材料:钢材 价格:410
家具类型:床 主材料:木材 价格:1280
家具类型:床 主材料:竹子 价格:1280
可是我编译后的输出结果却是:
家具类型: 主材料:木材 价格:870
(下同)
家具类型的这一部分没有输出,请问问题出在什么地方?
[此贴子已经被作者于2016-9-2 15:20编辑过]