Effective C++ Declarations – name & type

Effective C++ 55 Specific Ways to Improve Your Programs and Designs

Declarations – name & type

extern int x; // object declaration
// function declaration, also signature
std::size_t numDigits(int num);
class Widget; // class declaration
// template declaration
template
class GraphNode;
Definition – details
int x; // object definition – memory
// function definition – body
std::size_t numDigits(int num)
{ … }
// class and template definitions, include
// methods and data
class Widget{
public:
// list of methods, data…
};
template
class GraphNode {
public:
// list of methods, data ..
};
Initialization – give first value
Default constructor – no arguments (may be constructor with all default arguments)
Recommendation: make constructor explicit, to avoid implicit type conversions (example next slide)

EXPLICIT EXAMPLE

class A{
public:
A();
};
class B{
public:
explicit B(int x=0,
bool b=true);
};

class C{
public:
explicit C(int x);
// not a default
// constructor
};
void doSomething(B bObj);

// in main…
B bObj1;
doSomething(bObj1); // fine

B bObj2(28);
doSomething(bObj2); // fine

doSomething(28); // error!
doSomething(B(28));
// fine, uses B constructor
// explicitly

Cours gratuitTélécharger le cours complet

Télécharger aussi :

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *