How to set inherited C++ class/struct variables in single declaration
Is there a method I can use to be able to declare a new object w/ inherited variables with a single line of code? Example:
#include <iostream>
using namespace std;
struct item_t {
string name开发者_Go百科;
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;
}
Classes with inheritance are not POD and therefore are definitely not aggregates. If you are not using virtual functions, prefer composition to inheritance.
struct item_t {
string name;
string desc;
double weight;
};
struct hat_t
{
item_t item;
string material;
double size;
};
int main ()
{
// this is also OK
item_t hammer = {"Hammer", "Used to hit things", 6.25};
// this is now valid
hat_t cowboy = {"Cowboy Hat", "10 gallon hat", 4.5, "straw", 6.5};
return 0;
}
I believe having base classes prevents the aggregate initialization syntax in C++03. C++0x has more general initialization using braces, and so it is more likely to work there.
Can you maybe just use a constructor?
struct item_t {
item_t(string nameInput, string descInput, double weightInput):
name(nameInput),
desc(descInput),
weight(weightInput)
{}
string name;
string desc;
double weight;
};
struct hat_t : item_t
{
hat_t(string materinInput,d double sizeInput string nameInput, string descInput, double weightInput) :
material(materialInput), size(size), item_t(nameInput, descInput, weightInput)
{}
string material;
double size;
};
then you can just call the constructor you want.
精彩评论