C++核心準(zhǔn)則C.167:為具有約定俗成?語義的操作使用運(yùn)算符

C.167: Use an operator for an operation with its conventional meaning
C.167:為具有約定俗成語義的操作使用運(yùn)算符
Reason(原因)
Readability. Convention. Reusability. Support for generic code。
可讀性。遵守慣例??蓮?fù)用性。支持泛化代碼。
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?<
如果只考慮自己的話,cout_my_class還不錯(cuò),但是它無法在通過<<運(yùn)算符輸出的代碼中使用(或者和這樣的代碼一起使用)。
My_class var { /* ... */ };
// ...
cout << "var = " << var << '\n';Note(注意)
There are strong and vigorous conventions for the meaning most operators, such as
很多操作符具有強(qiáng)烈而且活躍的約定含義,例如:
comparisons (==,?!=,?<,?<=,?>, and?>=),
比較運(yùn)算符
arithmetic operations (+,?-,?*,?/, and?%)
數(shù)學(xué)運(yùn)算符
access operations (.,?->, unary?*, and?[])
訪問運(yùn)算符
assignment (=)
賦值運(yùn)算符
Don't define those unconventionally and don't invent your own names for them.
不要違反慣例定義這些運(yùn)算符,也不要為它們發(fā)明新名稱。
Enforcement(實(shí)施建議)
Tricky. Requires semantic insight.
不容易。需要語義方面的深入理解。
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c167-use-an-operator-for-an-operation-with-its-conventional-meaning
覺得本文有幫助?請分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
