《大规模C++程序设计》读书笔记24

本文探讨了C++中运算符重载的原则与指导方针,强调了运算符重载应注重可读性和自然性,避免不一致的问题,并提供了基本运算符属性的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 原则92:可读性(不仅仅是易用性)应该是使用运算符重载的主要原因。

指导方针11:一个重载运算符的语义对客户应该是自然的、明显的和直观的。

指导方针12:用户自定义类型的重载运算符的语法属性,应该反映已经为基本类型定义了的属性。

原则93:让用户自定义运算符的语法属性模仿预先确定的C++运算符,以避免意外并使它们的使用更可预知。

一些基本运算符属性的总结:

					// operators with similar declarations
class T {
	T& operator++();		// ++x --x (prefix)
	T operator++(int);		// x++ x-- (postfix)

	T* operator&();		        // &x (unary)
	const T* operator&() const;	// &x (unary)

	T& operator=(const T&);	        // = += -= *= /= %= <<= >>= &= ^= |=
};

T operator-(const T&);		        // - + ~ (unary)
int operator!(const T&);		// ! (unary)

T operator+(const T&, const T&);	// + - * / << >> % & ^ |
int operator==(const T&, const T&);	// == != < <= > >=
int operator&&(const T&, const T&);	// && ||

// if the type is pointer-like (i.e., P = T*)
class P {
	T& operator[](int) const;	// indexed array access (binary)
	T& operator*() const;	        // pointer dereference (unary)
};

// if the type is pointer-to-const-like (i.e., PC = const T*)
class PC {
	const T& operator[](int) const;	// indexed array access (binary)
	const T& operator*() const;	// pointer dereference (binary)
};
原则94:C++语言本身可以作为用户自定义运算符模仿的一个客观和适宜的标准。
原则95:重载运算符中的不一致问题,对客户来说可能是明显的、讨厌的和高代价的。
C++要求下列运算符是成员:
=       赋值
[]      下标
->      类成员访问
()      函数调用
(T)     转换("cast")运算符
new     (静态)分配运算符
delete  (静态)删除运算符
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

俞凡 DeepNoMind

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

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

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

打赏作者

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

抵扣说明:

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

余额充值