C++学习系列六:Classes(II)||overload operator||this||static members||const member functions||special membe

  • Overloading operators

Classes, essentially, define new types to be used in C++ code. And types in C++ not only interact with code by means of constructions and assignments. They also interact by means of operators. For example, take the following operation on fundamental types:

int a, b, c;
a = b + c;

Here, different variables of a fundamental type (int) are applied the addition operator, and then the assignment operator. For a fundamental arithmetic type, the meaning of such operations is generally obvious and unambiguouse, but it may not be so for certain class types. For example :

struct myclass {
    string product;
    float price;
} a, b, c;
a = b + c;

HEre, it is not obvious that the result of the addition operation on b and c dose. In fact, this code alone would cause a compilation error, since the type myclass has no defined behavior for additions.However, C++ allows most operators to be overloaded so that their behavior can be defined for just about any type, including classes. Here is a list of all the operators that can be overloaded:

Overloadable Operators
+ - * / = < > += -= *= /= << >> <<= >>= == != <= >= ++ – % & ^ !

Operators are overloaded by means of operator functions , which are regular functions with special names: their name begins by the operator keyword followed by the operator sign that is overloaded. THe syntax is :

type operator sign(parameters) {/*...body...*/}

For example, cartesian vectors are sets of two coordinates: x and y. The addition operation of two cartesian vector is defined as the addition both x coordinates together, and both y coordinates together. For example, adding the cartesian vectors (3, 1) and (1, 2) together would result in (3+1, 2+1) = (4,3). This could be implemented in C++ with the following code:

// overloading operators example
#include <iostream>
using namespace std;

class CVector {
  public:
    int x,y;
    CVector () {};
    CVector (int a, int b) : x(a), b(y) {}
    CVector operator + (const CVector&);
};
CVector CVector::operator+ (const CVector& param) {
    CVector temp;
    temp.x = x + param.x;
    temp.y = y + param.y;
    return temp;
}

int main () {
    CVector foo (3,1);
    CVector bar (1,2);
    CVector result;
    result = foo + bar;
    cout << result.x << ',' << result.y <<'\n';
    return 0;
}

If confused about so many appearances of CVector, consider that some of them refer to the class name (i.e., the type) CVector and some others are functions with that name (i.e., constructors, which must have the same name as the class). For example:

CVector (int, int) : x(a), y(b) {}   // function name CVector (constructor)
CVector operator + (const CVector&); // function that returns a CVector

THe function operator+ of class CVector overloads the addition operator (+) for that type. Once declared, this function can be called either implicitly using the operator, or explicitly using its functional name:

c = a + b;
c = a.operator + (b);
  • THe keyword this

The keyword this represents a pointer to the object whose member function is being executed. It is used within a class’s member function to refer to the object itself.

One of its uses can be to check if a parameter passed to a member function is the object itself. For example:

// example on this
#include <iostream>
using namespace std;

class Dummy {
  public:
    bool isitme (Dummy& param);
};

bool Dummy::isitme (DUmmy& param)
{
    if (&param == this) return true;
    else return false;
}

int main () {
    Dummy a;
    Dummy* b = &a;
    if ( b->isitme(a))
        cout << "yes, &a is b\n";
    return 0;
}

It is also frequently used in operator= member functions that return objects by reference.

  • Static members

A class can contain static members, either data or functions.

A static data member of a class is also known as a “class variable, because there is only one common variable for all the objects of that same class, sharing the same value; i.t., its value is not different from one object of this class to another.

class Dummy {
  public:
    static int n;
    DUmmy () {n++};
};
...

In fact, static members have the same properties as non-member variables but they enjoy class scope. For that reason, and to avoid them to be declared several times, they cannot be initialized directly in the class, but need to be initialized somewhere outside it.

Classes can also have static member functions. THese represent the same: members of a class that are common to all object of that class, acting exactly as non-member functions but besing accessed like members of the class. Because they are like non-member functions, they cannot access non-static members of the class (neither member variables nor member functions). They neither can use the keyword this.

  • Const member functions

WHen an object of a class is qualified as a const object:

const MyClass myobject;

THe access to its data members from outside the class is restricted to read-only, as if all its data members were const for those accessing them from outside the class. Note though, that the constructor is still called and is allowd to initialize and modify these data members.

The member functions of a const object can only be called if they are themselves specified as const members.

const objects are limited to access only member functions marked as const, but non-const objects are not restricted and thus can access both const and non-const member functions alike.

  • Class templates

Just like we can create function templates, we can also create class templates, allowing classes to have members that use template parameters as types.

template <class T>
class mypair {
    T value [2];
  public:
    mypair (T first, T second)
    {
        values[0] = first; value[1] = second;
    }
}

The class that we have just defined serves to store two elements of any valid type.

  • Template specialization

It is possible to define a different implementation for a template when a specific type is passed as templated argument. This is called a template specialization.

template <class T> class mycontainer {...};
template <> class mycontainer <char> {...};

The first line is the generic template, and the second one is the specialization.

When we declare specializations for a template class, we must also define all its members, even those identical to the generic template class, because there is no “inheritance” of members from the generic template to the specialization.

  • Special members

    Special member functions are member functions that are implicitly defined as member of classes under certain circumstances. There are six:

    Member function Typical form for class C
    Default constructor C::C();
    Destructor C::~C()
    Copy constructor C::C (const C&)
    Copy assignment C& operator=(const C&)
    Move constructor C::C (C&&)
    Move assignment C& operator=(C&&);
  • Friendship and inheritance

  • Friend functions

In principle, private and protected members of a class cannot be accessed from outside the same class in which they are declared. However, this rule does not apply to “friends”.

Friends are functions or classes declared with the friend keyword.

A non-member function can access the private and protected members of a class if it is declared a friend of that class. That is done by including a declaration of this external function within the class, and preceding it with the keyword friend.

class Rectangle {
    friend Rectangle duplicate (const Rectangle&);
}

  • Friend classes

Similar to friend functions, a friend class is a class whose members have access to the private or protected members of another class.

class Rectangle {
   ...  
}
class Square {
    friend class Rectangle;
    ...
}

  • Inheritance between classes

Classes in C++ can be extended, creating new classes which retain characteristics of the base class. This process, known as inheritance, involves a base class and a derived class: The derived class inherits the members of the base class, on top of which it can add its own members.

  • What is inherited from the base class?

In principle, a publicly derived class inherits access to every member of a base class except:

	1. its constructors and its destuctor


 		2. its assignment operator members (operator=)
           		3. its friends
                     		4. its private members
  • Multiple inheritance

A class may inherit from more than one class by simply specify more base classes, separated by commas, in the list of a class’s base classes (i.e., after the colon). For example, if the program had a specific class to print on screen called Output, and we wanted our classes Rectangle and Triangle to also inherit its members in addition to those of Polygon we could write:

class Rectangle: public Polygon, public Output;
class Triangle: public Polygon, public Output;

  • Polymorphism

Before getting any deeper into this chapter, you should have a proper understanding of pointers and class inheritance.

  • Pointers to base class

One of the key features of class inheritance is that a pointer to a derived class is type-compatible with a pointer to its base class. Polymorphism is the art of taking advantage of this simple but powerful and versatile feature.

  • Virtual members

A virtual member is a member function that can be redefined in a derived class, while preserving its calling properties through references. The syntax for a function to become virtual is to precede its declaration with the virtual keyword.

  • Abstract base classes

Abstract base classes are something very similar to the Polygon class . They are classes that can only be used as base classes, and thus are allowed to have virtual member functions without definition (known as pure virtual functions). The syntax is to replace their definition by =0 (an euqal sign and a zero).

猜你喜欢

转载自blog.csdn.net/The_Time_Runner/article/details/107304745