How can I declare constructor for a struct? My struct is declared in the private part of a class and I want to declare my constructor for it.
Below is my code
class Datastructure {
private:
struct Ship
{
std::string s_class;
std::string name;
unsigned int length;
} minShip, maxShip;
std::vector<Ship> shipVector;
public:
Datastructure();
~Datastructure();
};
This my header file; how can I declare constructor for my struct Ship and where do I have to implement that constructor in .h file or in cpp file?
Constructor declared in header file
struct Ship
{
Ship();
std::string s_class;
std::string name;
unsigned int length;
} minShip, maxShip;
and implemented in code:
DataStructure::Ship::Ship()
{
// build the ship here
}
or more likely:
DataStructure::Ship::Ship(const string& shipClass, const string& name,
const unsigned int len) :
s_class(shipClass), name(_name), length(len)
{
}
with this in the header:
struct Ship
{
private:
Ship();
public:
Ship(const string& shipClass, const string& name, unsigned len);
std::string s_class;
std::string name;
unsigned int length;
} minShip, maxShip;
You declare it the same way you declare any other constrctor
class Datastructure {
private:
struct Ship
{
std::string s_class;
std::string name;
unsigned int length;
Ship(); // <- here it is
} minShip, maxShip;
std::vector<Ship> shipVector;
public:
Datastructure();
~Datastructure();
};
And you define it the same way you define any other constructor. If it is inline, you define it in the header file. If it is not inline, you define it in implementation file
Datastructure::Ship::Ship()
{
// whatever
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With