有没有一种方法可以用一行代码来声明一个新的对象/继承变量?例如:如何在单个声明中设置继承的C++类/结构变量
#include <iostream>
using namespace std;
struct item_t {
string name;
string desc;
double weight;
};
struct hat_t : item_t
{
string material;
double size;
};
int main()
{
hat_t fedora; // declaring individually works fine
fedora.name = "Fedora";
fedora.size = 7.5;
// this is also OK
item_t hammer = {"Hammer", "Used to hit things", 6.25};
// this is NOT OK - is there a way to make this work?
hat_t cowboy = {"Cowboy Hat", "10 gallon hat", 4.5, "straw", 6.5};
return 0;
}
我喜欢这个答案在我的,他是正确的总是使用组成,你可以。 – Craig 2011-03-14 00:59:11
太棒了!谢谢。我仍然在学习C++的功能。自学让我错过了一个教室会覆盖的很多东西。 – Zomgie 2011-03-14 01:07:07
@Zomgie你应该阅读Herb Sutter的C++编码标准。它有助于所有这些类型的东西。 – Craig 2011-03-14 01:11:58