c++运算符重载的一些理解

运算符重载类似于调用函数,对于用户定义的类,c++没有可以比较他们关系的运算符,所以就像定义函数那样来重载运算符。

#include <iostream>
using namespace std;
class Tricycle
{
public:
    Tricycle();
    // copy constructor and destructor use default
    int getSpeed() const { return *speed; }
    void setSpeed(int newSpeed) { *speed = newSpeed; }
    //Tricycle operator=(const Tricycle&);
    bool operator==(const Tricycle&);           //congzai==
  
private:
    int *speed;
};
  
Tricycle::Tricycle()
{
    speed = new int;
    *speed = 5;
}

bool Tricycle::operator==(const Tricycle& rhs)
{
    if (this==&rhs)
    {
        return true;
    }
    if(this->getSpeed()>=rhs.getSpeed())    
    {
        return true;                  //if getSpeed()>=rhs.getSpeed()  return ture
    }
    return false;
}
  
/*Tricycle Tricycle::operator=(const Tricycle& rhs)
{
    if (this == &rhs)
        return *this;
    delete speed;
    speed = new int;
    *speed = rhs.getSpeed();
    return *this;
}*/
  
int main()
{
    Tricycle wichita;
    std::cout << "Wichita's speed: " << wichita.getSpeed() 
        << "\n";
    std::cout << "Setting Wichita's speed to 8 ...\n";
    wichita.setSpeed(8);
    Tricycle dallas;
    std::cout << "Dallas' speed: " << dallas.getSpeed() 
        << "\n";
    std::cout << "Setting Dallass speed to 7 ...\n";
    dallas.setSpeed(7);
    cout<<"wichita.getSpeed= "<<wichita.getSpeed()<<endl;

    cout<<"dallas.getSpeed= "<<dallas.getSpeed()<<endl;
    if(wichita == dallas)
    {
        cout<<"Wichita speed>=Dallass speed\n";   //houmiande xiao fanhui ture
    }
    else
    {
        cout<<"Wichita speed < Dallas speed\n";
    }


    return 0;
}

其中,就像函数那样,此处是重载==运算符,但是并非是判断相等的,而是判断两个对象中的speed成员变量是否是运算符==左侧的>=右侧的,返回一个bool类型,通过调用运算符,打印他们之间的关系。

下面是重载=运算符的例子:

#include <iostream>
  
class Tricycle
{
public:
    Tricycle();
    // copy constructor and destructor use default
    int getSpeed() const { return *speed; }
    void setSpeed(int newSpeed) { *speed = newSpeed; }
    Tricycle operator=(const Tricycle&);
  
private:
    int *speed;
};
  
Tricycle::Tricycle()
{
    speed = new int;
    *speed = 5;
}
  
Tricycle Tricycle::operator=(const Tricycle& rhs)
{
    if (this == &rhs)
        return *this;
    delete speed;
    speed = new int;
    *speed = rhs.getSpeed();
    return *this;
}
  
int main()
{
    Tricycle wichita;
    std::cout << "Wichita's speed: " << wichita.getSpeed() 
        << "\n";
    std::cout << "Setting Wichita's speed to 6 ...\n";
    wichita.setSpeed(6);
    Tricycle dallas;
    std::cout << "Dallas' speed: " << dallas.getSpeed() 
        << "\n";
    std::cout << "Copying Wichita to Dallas ...\n";
    wichita = dallas;
    std::cout << "Dallas' speed: " << dallas.getSpeed() 
        << "\n";
    return 0;
}

ps:内容来自c++入门经典的源代码

猜你喜欢

转载自blog.csdn.net/suyunzzz/article/details/89923123