Operatory to specjalne funkcje. Specjalne, bo można je wywołać za pomocą określonego w nazwie operatora. Popatrz na przykład.
class Person {
const std::string name_;
unsigned age_;
public:
Person(const std::string & name, unsigned age)
: name_(name), age_(age)
{}
unsigned getAge() const { return age_; }
Person& operator++() {
age_++;
return *this;
}
};int main() {
Person adam("Adam", 25);
++adam;
std::cout << adam.getAge() << '\n'; // prints 26
}T& T::operator +=(const T2& b);Computer& Computer::operator+=(Memory amount) {
ramAmount_ += amount;
std::cout << "Ram memory extended\n";
return *this;
}Computer hp{}; // default configuration
hp += Memory{8_GB};Tego nie rób:
Computer Computer::operator+=(Memory amount) {
ramAmount_ -= amount;
std::cout << "Ram memory extended\n";
}Powyższy kod zawiera 3 błędy.
-
Wewnątrz operatora
+=użyliśmy-=. Nikt nie spodziewa się takiego zachowania. Brakuje tylko komentarza// happy debugging -
Brakuje nam
return *this. W końcu coś zwracamy, prawda? Kompilatory na szczęście ostrzegają przed tym problemem. -
Zwracamy kopię.
operator+=powinien zwracać referencję do obiektu, aby działał tak jak każdy inny standardowyoperator+=
Mamy ich całkiem sporo
Zobacz operatory na cppreference.com
Operatory możesz też wywołać pisząc "nazwę funkcji".
Computer hp{}; // default configuration
hp += Memory{8_GB};
hp.operator+=(Memory{8_GB}); // equal to aboveMożesz przeciążyć (zaimplementować) prawie każdy operator, z wyjątkiem:
-
. -
.* -
:: -
?: -
# -
## -
sizeof -
typeid
