class T
{
public:
const tClass& val() const { return _val; }
tClass & val() const { return _val; }
}
2. a good practice - make sure two class objects are not the same when copying
T& T::copy(const T& rhs)
{
if (this != &rhs)
{
_var1 = rhs._var1;
_var2 = rhs._var2;
}
return *this;
}
3. static class members - the single, shared instance that is accessible to all the objects of that class (static members); don't access any non-static class members (static member functions)
---T.h
class T
{
public:
static bool is_elem(int);
private:
static vector _elements; // we need to put its explicit definition within a .cpp file
static const int _var1 = 1024; // no need to do that
}
---T.cpp
vector T::_elements;
bool T::is_elem(int val) { ... _elements ...} // only access static members
---Main.cpp
if (T::is_elem()) {}
4. constructor, copy constructor, copy assignment operator ...
copy assignment -
M& M::operator= (const M& rhs)
{
if (this != &rhs)
{
delete [] _elem;
_elem = new double [cnt];
for(int ix=0;ix != cnt; ++ix)
_elem[ix] = rhs._elem[ix];
}
return *this;
}
5. function object - an object of a class that has an instance of the function call operator
class LessThan
{
public:
LessThan(int val):_val(val) {}
int comp_val() const {return _val;}
void comp_val(int nval) {_val = nva;}
bool operator() (int value) const;
private:
int _val;
}
inline bool LessThan::operator() (int value) const
{ return value "<" _val; }
int count_less_than(const vector& vec, int comp)
{
LessThan lt(comp);
int count = 0;
for (int ix=0;ix!=vec.size();++ix)
{
if(lt(vec[ix])) ++count;
}
return count;
}
No comments:
Post a Comment