关于>?和<?运算符

昨天又看到群里有人问这个运算符,特意google了一下。


这是gcc的扩展运算符,原文在此

http://gcc.gnu.org/onlinedocs/gcc-3.2.3/gcc/Min-and-Max.html


简单说 a >? b就是 max( a, b ),a <? b就是min( a, b )

a >?= b 就是 a = max( a, b )

a <?= b 就是 a = min( a, b )


据说这种符号已经废弃了,建议用std::min和std::max

### C++ 类中重载 `>>` `<<` 运算符的相关题型与教程 在C++中,运算符重载是一种强大的功能,允许程序员为自定义类定义特殊的行为。对于输入/输出运算符(`>>` `<<`),它们通常被用于实现类对象的流式输入输出。以下是关于如何重载这两个运算符的详细说明代码示例。 #### 1. 运算符重载的基本概念 运算符重载是通过定义一个函数来实现的,该函数的名称以关键字 `operator` 开头,后接要重载的运算符符号。例如,重载 `<<` `>>` 运算符时,需要分别定义它们作为友元函数或成员函数[^5]。 #### 2. 重载 `<<` 运算符 `<<` 运算符通常用于将对象的内容输出到标准输出流(如 `cout`)。为了实现这一点,可以将 `<<` 定义为友元函数,这样它就可以访问类的私有成员。 ```cpp #include <iostream> using namespace std; class Complex { private: double real; double imag; public: Complex(double r = 0, double i = 0) : real(r), imag(i) {} // 声明友元函数 friend ostream& operator<<(ostream& os, const Complex& c); }; // 定义友元函数 ostream& operator<<(ostream& os, const Complex& c) { os << c.real << " + " << c.imag << "i"; return os; } int main() { Complex c(3.5, 4.2); cout << "Complex number: " << c << endl; // 输出复数 return 0; } ``` #### 3. 重载 `>>` 运算符 `>>` 运算符通常用于从标准输入流(如 `cin`)读取数据并存储到对象中。同样,可以通过友元函数实现这一功能。 ```cpp #include <iostream> using namespace std; class Point { private: double x, y; public: Point(double a = 0, double b = 0) : x(a), y(b) {} // 声明友元函数 friend istream& operator>>(istream& is, Point& p); }; // 定义友元函数 istream& operator>>(istream& is, Point& p) { cout << "Enter x and y coordinates: "; is >> p.x >> p.y; return is; } int main() { Point p; cin >> p; // 输入点的坐标 cout << "Point entered: (" << p.x << ", " << p.y << ")" << endl; return 0; } ``` #### 4. 注意事项 - **返回值类型**:重载 `<<` `>>` 运算符时,返回值类型应为 `ostream&` `istream&`,以便支持链式操作(如 `cout << obj1 << obj2`)。 - **友元函数**:由于输入/输出运算符通常涉及多个参数(如流对象用户定义的对象),因此推荐使用友元函数而非成员函数[^6]。 #### 5. 综合示例 以下是一个综合示例,展示如何同时重载 `<<` `>>` 运算符: ```cpp #include <iostream> #include <string> using namespace std; class Student { private: string name; int age; public: Student(string n = "", int a = 0) : name(n), age(a) {} // 声明友元函数 friend ostream& operator<<(ostream& os, const Student& s); friend istream& operator>>(istream& is, Student& s); }; // 定义友元函数 ostream& operator<<(ostream& os, const Student& s) { os << "Name: " << s.name << ", Age: " << s.age; return os; } istream& operator>>(istream& is, Student& s) { cout << "Enter name and age: "; is >> s.name >> s.age; return is; } int main() { Student s; cin >> s; // 输入学生信息 cout << "Student details: " << s << endl; // 输出学生信息 return 0; } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值