摘自C++ primer
operator being defined
一個賦值操作符的例子
class Sales_item {
public:
// other members as before
// equivalent to the synthesized assignment operator
Sales_item& operator=(const Sales_item &);
};
// equivalent to the synthesized assignment operator
Sales_item&
Sales_item::operator=(const Sales_item &rhs)
{
isbn = rhs.isbn; // calls string::operator=
units_sold = rhs.units_sold; // uses built-in int assignment
revenue = rhs.revenue; // uses built-in double assignment
return *this;
}
Most operators may be defined as member or nonmember functions. When an operator is a member function, its first operand is implicitly bound to the this pointer. Some operators,assignment among them, must be members of the class
for which the operator is defined.Usually, the right-hand operand is passed as a const reference
大多數操作符既可以定義成成員操作符,也可以定義成非成員操作符。當一個操作符定義成成員函數的時候,第一個操作數隱式綁定到this指針。某些操作符,比如它們中的賦值操作符,必須是該定義的操作符所在類的成員函數
右操作符通常情況下是const引用。
With the exception of the function-call operator, an overloaded operator has the same number
of parameters (including the implicit this pointer for member functions) as the operator has
operands. The function-call operator takes any number of operands.
// member binary operator: left-hand operand bound to implicit this pointer
Sales_item& Sales_item::operator+=(const Sales_item&);
// nonmember binary operator: must declare a parameter for each operand
Sales_item operator+(const Sales_item&, const Sales_item&);
When an operator is a member function, this points to the left-hand operand. Thus, the
nonmember operator+ defines two parameters, both references to const Sales_item objects.
Even though compound assignment is a binary operator, the member compound-assignment
operator takes only one (explicit) parameter. When the operator is used, a pointer to the lefthand
operand is automatically bound to this and the right-hand operand is bound to the
function's sole parameter.
It is also worth noting that compound assignment returns a reference and the addition operator
returns a Sales_item object. This difference matches the return types of these operators when
applied to arithmetic types: Addition yields an rvalue and compound assignment returns a
reference to the left-hand operand.
賦值操作符返回的是Sale_item引用類型,+操作符返回的是Sale_item類型
概念3:虛函數virtual function
#include<iostream>
using namespace std;
class Vehicle{
public:
virtual void run(){
cout<<"Vehicle run"<<endl;
}
};
class Car:public Vehicle{
public:
void run(){
cout<<"Car run"<<endl;
}
};
int main(){
Car c;
Vehicle *v=&c;
v->run(); //invocate Car's run method
}