| jojo212 (30) | ||||||
|
Hi Guys, Having a very weird issue. I know I've done this a million times and never gotten an error, not sure why I'm getting one now. Basically, being told I need a default constructor to make a basic struct. Here's the code:
And here's the error:
The bizarre thing is that I have another class in the same project that is literallyan exact copy of this one except it's for a different type of object (passenger) and that one compiles without a problem. As a solution, I tried declaring the struct like this:
But then I get an error that I needed a constructor Train() for that to work. Anyone know why I'm having this problem? Much thanks! | ||||||
|
Last edited on
|
||||||
| Disch (8338) | |
|
Train might not have a default constructor, which means that a tNode object cannot be constructed without explicitly calling a separate ctor for it. Can you post your Train class? Or really just the constructor(s). | |
|
|
|
| jojo212 (30) | |||||||||
It won't let me make a default constructor for Train, because the non-default constructors take references at parameters. Like this:
When I try to write an empty default constructor JUST for the node:
I get this error:
So I tried doing this:
But then I get this error:
So not sure what to do here. | |||||||||
|
|
|||||||||
| Disch (8338) | |
|
Okay that's your problem. References need to be constructed explicitly (they do not have a default constructor). So since your Train class has references as members, you would need to initialize them in your default constructor. However that's difficult/impossible to do correctly because I assume the stuff is supposed to be referencing things outside the class. This is one of the reasons why I generally don't have reference as class members. It's rarely justifiable. I recommend changing trainline and passMan to be pointers instead of references. Then in your default constructor initialize them to null (do not allocate with new -- that makes little/no sense). This also means you'll have to have some other kind of initialize function where you can set these members. | |
|
|
|
| ne555 (4038) | |||
|
Or, write a copy constructor for `Train' that copies the references. Use it to construct your nodes. There's still the problem of your dummy header, use a dummy node for that.
whenever you need to access the `data' field, just cast the node (it's an error to want to cast the header cell). Don't force a default constructor if it makes no sense. | |||
|
|
|||