简介
在类比较方面,三目运算符可以用于重载比较运算符。
代码示例1
#include <iostream>
#include <cstring>
class Person {
public:
  Person(const char* name, int age) : m_age(age) {
    m_name = new char[strlen(name) + 1];
    strcpy(m_name, name);
  }
  ~Person() {
    delete[] m_name;
  }
  bool operator==(const Person& other) const {
    return m_age == other.m_age && strcmp(m_name, other.m_name) == 0;
  }
  bool operator!=(const Person& other) const {
    return !(*this == other);
  }
private:
  char* m_name;
  int m_age;
};
int main() {
  Person john("John", 25);
  Person jane("Jane", 27);
  Person john2("John", 25);
  std::cout << "john == jane: " << ((john == jane) ? "true" : "false") << std::endl;
  std::cout << "john != jane: " << ((john != jane) ? "true" : "false") << std::endl;
  std::cout << "john == john2: " << ((john == john2) ? "true" : "false") << std::endl;
  return 0;
}
 
输出结果如下

代码实例2
三目运算符可以在继承类中使用,与之前的示例演示无异。比较运算符重载同样可以在继承类中使用,子类可以重载父类的比较运算符。例如,以下是一个使用继承和比较运算符重载的例子
#include <iostream>
#include <cstring>
class Person {
public:
  Person(const char* name, int age) : m_age(age) {
    m_name = new char[strlen(name) + 1];
    strcpy(m_name, name);
  }
  ~Person() {
    delete[] m_name;
  }
  bool operator==(const Person& other) const {
    return m_age == other.m_age && strcmp(m_name, other.m_name) == 0;
  }
protected:
  char* m_name;
  int m_age;
};
class Student : public Person {
public:
  Student(const char* name, int age, int score) : Person(name, age), m_score(score) {}
  bool operator==(const Student& other) const {
    return Person::operator==(other) && m_score == other.m_score;
  }
private:
  int m_score;
};
int main() {
  Person john("John", 25);
  Person jane("Jane", 27);
  Student john2("John", 25, 90);
  Student john3("John", 25, 91);
  std::cout << "john == jane: " << ((john == jane) ? "true":"false") << std::endl;
  std::cout << "john == john2: " << ((john == john2) ? "true" : "false") << std::endl;
  std::cout << "john2 == john3: " << ((john2 == john3) ? "true" : "false") << std::endl;
  return 0;
}
 
在这个示例中,我们定义了两个类 Person 和 Student,Student 类继承自 Person 类,并添加了一个名为 m_score 的成员变量和一个名为 operator== 的比较运算符重载。在 operator== 函数中,我们首先调用基类的 operator== 方法,然后比较 m_score 的值。
输出结果如下




















