Using string object in a struct

Started by
5 comments, last by JGailor 20 years, 3 months ago
Can you use a string object (non-pointer) in a struct? I realize that structs need to know their size at run-time, and that using a string means you can have a varying memory footprint, but I was just wondering if this was possible. I would normally just use a string *, but the values are one time initializations that don''t necessarily need the overhead of creating using new/delete. And I could use char[] but I''m trying to migrate away from mixing the two (no real reason, just personal preference).
Advertisement
You can certainly use strings. The size of your class won''t change since the string just holds an internal char* and re-sizes the memory that points to internally as needed.
thankyou. that''s good information to know.
Still having problems. Allow me to post the code snippet, and see if someone can diagnose my problem.

// Structs
typedef struct {
string title;
unsigned copyright;
string author;
string publisher;
}booksTag;


// Data members
HINSTANCE ghInstance;
string strWinName = "DialogBoxes1";
string strWinTitle = "Using Dialog Boxes - 1";

booksTag booksTags[NUMBOOKS] = {
{ "C++: The Complete Reference",
1998, "Herbert Schildt", "Osborne/McGraw-Hill" },
{ "MFC Programming from the Ground Up", 1998, "Herbert Schildt", "Osborne/McGraw-Hill" },
{ "Java: The Complete Reference", 1999, "Naughton and Schildt", "Osborne/McGraw-Hill" },
{ "The C++ Programming Language", 1997, "Bjarne Stroustrup", "Addison-Wesley" },
{ "Inside OLE", 1995, "Kraig Brockschmidt", "Microsoft Press" },
{ "HTML Sourcebook", 1996, "Ian S. Graham", "John Wiley & Sons" },
{ "Standard C++ Library", 1995, "P. J. Plauger", "Prentice-Hall" }
};

giving me numerous errors:

error C2440: ''initializing'' : cannot convert from ''char [28]'' to ''booksTag''
No constructor could take the source type, or constructor overload resolution was ambiguous
Since you are using C++ anyway (std::string), why not make an constructor? It could look something like this:

struct books{public:  books(const char* t, unsigned c, const char* a, const char* p)    : title(t), copyright(c), author(a), publisher(p)  {}private:  string title;  unsigned copyright;  string author;  string publisher;};
I don''t have any problem with that, I was just wondering why it was having a heart attack with the way I was doing it.

The constructor does in fact solve the problem though. Thanks for the help.
Partially because "string" is not of type std::string, but of type char*. You maybe could have said

{ string("Inside OLE"), 1995, string("Kraig Brockschmidt"), string("Microsoft Press") },

but that wouldn''t work in this particular case either, because std::string has constructors which the compiler doesn''t like for aggregate definitions.

In the end, the constructor is the way.

I like pie.
[sub]My spoon is too big.[/sub]

This topic is closed to new replies.

Advertisement