Inheritance C++;结构继承项系统
我正在尝试为一个辅助项目创建一个项目系统,并且正在测试结构中的继承。这并没有给我预期的结果:Inheritance C++;结构继承项系统,inheritance,struct,Inheritance,Struct,我正在尝试为一个辅助项目创建一个项目系统,并且正在测试结构中的继承。这并没有给我预期的结果: struct Item { int price; int id; }; struct Iron : Item { int price = 10; int id = 1; }; struct Gold : Item { int price = 15; int id = 2; }; int main() { std::cout << "Hello World!
struct Item
{
int price;
int id;
};
struct Iron : Item
{
int price = 10;
int id = 1;
};
struct Gold : Item
{
int price = 15;
int id = 2;
};
int main()
{
std::cout << "Hello World!\n";
Item testItem = Iron();
std::cout << "Item price: " << testItem.price << ", Item ID: " << testItem.id << std::endl;
testItem = Gold();
std::cout << "Item price: " << testItem.price << ", Item ID: " << testItem.id << std::endl;
}
<> P> >在C++中不允许重写成员变量< < /P> 当您声明
Iron::price
时,您会在其中隐藏Item::price
这样做:
struct Item
{
int price;
int id;
};
struct Iron : Item
{
Iron() {price = 10, id = 1; }
};
struct Gold : Item
{
Gold() { price = 15, id = 2; }
};
int main()
{
std::cout << "Hello World!\n";
Item testItem = Iron();
std::cout << "Item price: " << testItem.price << ", Item ID: " << testItem.id << std::endl;
testItem = Gold();
std::cout << "Item price: " << testItem.price << ", Item ID: " << testItem.id << std::endl;
}
struct项
{
国际价格;
int-id;
};
结构铁:项目
{
Iron(){price=10,id=1;}
};
结构黄金:项目
{
Gold(){price=15,id=2;}
};
int main()
{
标准::cout
struct Item
{
int price;
int id;
};
struct Iron : Item
{
Iron() {price = 10, id = 1; }
};
struct Gold : Item
{
Gold() { price = 15, id = 2; }
};
int main()
{
std::cout << "Hello World!\n";
Item testItem = Iron();
std::cout << "Item price: " << testItem.price << ", Item ID: " << testItem.id << std::endl;
testItem = Gold();
std::cout << "Item price: " << testItem.price << ", Item ID: " << testItem.id << std::endl;
}