温馨提示×

c++operator怎样使用

c++
小樊
83
2024-11-19 16:23:56
栏目: 编程语言

C++中的运算符(operator)是一种特殊的函数,用于执行特定的操作。它们允许我们以简洁的方式执行常见的操作,如加法、减法、乘法、除法等。运算符重载是C++中的一个重要特性,它允许我们为自定义类型(如类或结构体)定义运算符的行为。

以下是一些常见的使用运算符的例子:

  1. 算术运算符:
#include <iostream>

int main() {
    int a = 5;
    int b = 3;

    // 加法
    int sum = a + b;
    std::cout << "Sum: " << sum << std::endl;

    // 减法
    int diff = a - b;
    std::cout << "Difference: " << diff << std::endl;

    // 乘法
    int product = a * b;
    std::cout << "Product: " << product << std::endl;

    // 除法
    int quotient = a / b;
    std::cout << "Quotient: " << quotient << std::endl;

    return 0;
}
  1. 赋值运算符:
#include <iostream>

int main() {
    int a = 5;

    // 赋值运算符
    a = a + b;
    std::cout << "a after assignment: "<< a << std::endl;

    return 0;
}
  1. 比较运算符:
#include <iostream>

int main() {
    int a = 5;
    int b = 3;

    // 相等
    bool isEqual = (a == b);
    std::cout << "a == b: " << isEqual << std::endl;

    // 不等
    bool isNotEqual = (a != b);
    std::cout << "a != b: " << isNotEqual << std::endl;

    // 大于
    bool isGreater = (a > b);
    std::cout << "a > b: " << isGreater << std::endl;

    // 小于
    bool isLess = (a < b);
    std::cout << "a < b: " << isLess << std::endl;

    // 大于等于
    bool isGreaterOrEqual = (a >= b);
    std::cout << "a >= b: " << isGreaterOrEqual << std::endl;

    // 小于等于
    bool isLessOrEqual = (a <= b);
    std::cout << "a <= b: " << isLessOrEqual << std::endl;

    return 0;
}
  1. 逻辑运算符:
#include <iostream>

int main() {
    int a = 5;
    int b = 3;

    // 逻辑与
    bool isAnd = (a > 0 && b > 0);
    std::cout << "a > 0 && b > 0: " << isAnd << std::endl;

    // 逻辑或
    bool isOr = (a > 0 || b > 0);
    std::cout << "a > 0 || b > 0: " << isOr << std::endl;

    // 逻辑非
    bool isNot = !(a > 0);
    std::cout << "!a > 0: " << isNot << std::endl;

    return 0;
}
  1. 逗号运算符:
#include <iostream>

int main() {
    int a = 5;
    int b = 3;

    // 逗号运算符
    int result = (a = a + b, a);
    std::cout << "Result: " << result << std::endl;

    return 0;
}
  1. 自定义类型和运算符重载:
#include <iostream>

class Complex {
public:
    Complex(int real, int imag) : real_(real), imag_(imag) {}

    // 重载加法运算符
    Complex operator+(const Complex& other) const {
        return Complex(real_ + other.real_, imag_ + other.imag_);
    }

    // 重载输出运算符
    friend std::ostream& operator<<(std::ostream& os, const Complex& c) {
        os << "(" << c.real_ << ", " << c.imag_ << ")";
        return os;
    }

private:
    int real_;
    int imag_;
};

int main() {
    Complex c1(3, 2);
    Complex c2(1, 7);

    // 使用重载的加法运算符
    Complex sum = c1 + c2;
    std::cout << "c1 + c2: " << sum << std::endl;

    return 0;
}

在这个例子中,我们定义了一个表示复数的类Complex,并重载了加法运算符和输出运算符。这使得我们可以使用+运算符来添加两个复数对象,并使用<<运算符来输出复数的值。

0