开发者

How to use constructors in an implementation file?

I am writing a program that is meant to take user input for a class - Country - and cout the biggest country in terms of area as well as the most densely populated country. I am, however, having with the implementation file.

What should go into 开发者_开发知识库my default constructor? What about other constructors? This is what I have so far:

#ifndef COUNTRY_H
#define COUNTRY_H
#include <string>


class Country 
{
public:


   Country(string name, double area, int population);

   Country();

   string get_name () const;

   double get_area()const;

   int get_population()const;

   double population_density(Country popDensity) const;


   void largest_area(double a);

   void largest_population(int p);

   void most_dense(double d);


private:

    string name;
    double area;
    int population;

};

#endif

and:

#include <iostream>
#include <string>

using namespace std;

#include "COUNTRY_H"

Country :: Country(string name, double area, int population)
{

}

Country :: Country();
{

}


In this case, (and most cases) you are only initializing members, and want to use an initializer list.

Country: Country(string _name, double _area, int _population): name(_name),area(_area),population(_population)
{}

To improve readability for new coders, I've changed the argument names so that they do not match exactly the member variable names. The compiler will not be confused by identical argument and member names in an initializer list.

Your default constructor can have an initializer list with only default values, e.g. name("Transylvania"),area(5),population(42), but if it is difficult to think of meaningful default values, it is valid to leave the default constructor undefined so that the class requires values in order to be constructed.


There is a bunch of things wrong here.

  • your implementation includes a file with the name COUNTRY_H, I'd assume the include should be #include "Country.h"
  • never ever have a using namespace clause before any include statement, this can make for really ugly bugs
  • your constructor takes it's string parameter by value, but it should take it by const& (reference-to-const that is)

For the default ctor: It should set every member of the class to a sensible default. If you skip it, a default constructor will be generated and default construct every member, remember that primitive types (e.g. int, long) have initially undefined state. Also remeber that defining any constructor, will prevent the default constructor from being generated. Use initializer lists to initialize members of your class, don't do it in the body of the constructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜