c++ 三目运算符在类中的使用

简介

在类比较方面,三目运算符可以用于重载比较运算符。

代码示例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 的值。

输出结果如下

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路过的小熊~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值