C++核心准则C.167:为具有约定俗成语义的操作使用运算符
C.167: Use an operator for an operation with its conventional meaning
C.167:为具有约定俗成语义的操作使用运算符
Reason(原因)
Readability. Convention. Reusability. Support for generic code。
可读性。遵守惯例。可复用性。支持泛化代码。
Example(示例)
void cout_my_class(const My_class& c) // confusing, not conventional,not generic
{
std::cout << /* class members here */;
}
std::ostream& operator<<(std::ostream& os, const my_class& c) // OK
{
return os << /* class members here */;
}
By itself, cout_my_class would be OK, but it is not usable/composable with code that rely on the << convention for output:
如果只考虑自己的话,cout_my_class还不错,但是它无法在通过<<运算符输出的代码中使用(或者和这样的代码一起使用)。
My_class var { /* ... */ };
// ...
cout << "var = " << var << '\n';
Note(注意)
There are strong and vigorous conventions for the meaning most operators, such as
很多操作符具有强烈而且活跃的约定含义,例如:
comparisons (==, !=, <, <=, >, and >=),
比较运算符
arithmetic operations (+, -, *, /, and %)
数学运算符
access operations (., ->, unary *, and [])
访问运算符
assignment (=)
赋值运算符
Don't define those unconventionally and don't invent your own names for them.
不要违反惯例定义这些运算符,也不要为它们发明新名称。
Enforcement(实施建议)
Tricky. Requires semantic insight.
不容易。需要语义方面的深入理解。
原文链接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c167-use-an-operator-for-an-operation-with-its-conventional-meaning
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!