C++中的運算符(operator)是一種特殊的函數,用于執行特定的操作。它們允許我們以簡潔的方式執行常見的操作,如加法、減法、乘法、除法等。運算符重載是C++中的一個重要特性,它允許我們為自定義類型(如類或結構體)定義運算符的行為。
以下是一些常見的使用運算符的例子:
#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;
}
#include <iostream>
int main() {
int a = 5;
// 賦值運算符
a = a + b;
std::cout << "a after assignment: "<< a << std::endl;
return 0;
}
#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;
}
#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;
}
#include <iostream>
int main() {
int a = 5;
int b = 3;
// 逗號運算符
int result = (a = a + b, a);
std::cout << "Result: " << result << std::endl;
return 0;
}
#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
,并重載了加法運算符和輸出運算符。這使得我們可以使用+
運算符來添加兩個復數對象,并使用<<
運算符來輸出復數的值。