【发布时间】:2010-12-06 09:07:21
【问题描述】:
我正在关注一本书来学习 C++(来自 python 背景)。我已经写了这个,它有效:
class CatalogueItem
{
public:
CatalogueItem();
CatalogueItem(int item_code, const string &name, const string &description);
~CatalogueItem() {};
bool operator< (const CatalogueItem &other) const;
...
private:
...
};
...
list<CatalogueItem> my_list;
// this is just me playing around
CatalogueItem items[2];
items[0] = CatalogueItem(4, string("box"), string("it's a box"));
items[1] = CatalogueItem(3, string("cat"), string("it's a cat"));
my_list.push_back(items[0]);
my_list.push_back(items[1]);
my_list.sort();
我正在尝试的部分是使用运算符
这一切似乎都很好,但http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Operator_Overloading 似乎建议避免这样做,这正是本书所说的! (“特别是,不要重载 operator== 或 operator
我理解“创建相等和比较函子类型”是指创建比较函数,如下所示:
bool my_comparison_function(const CatalogueItem &a, const CatalogueItem &b)
{
// my comparison code here
}
这就是风格指南所指的吗?
有没有人可以选择哪种方法更“正确”?
J
【问题讨论】:
-
我不认为 Google 风格指南真的是最好的 C++ 指南集。如果您阅读它,他们会在几个部分中明确指出,做出决定是出于他们自己的内部原因,而不是因为他们“正确”。
-
Google 本质上对 C++ 有一种“无趣”的方法,这对于一个包含数千名才华横溢的程序员的组织来说可能是必要的,这些程序员必须以某种方式被说服以产生相互理解的 C++。但是他们的风格指南让我真的想知道他们为什么决定使用 C++,而不是 C 和一些约定来模拟虚拟调用的等价物。程序员把各种可能性摆在他们面前,然后把它们抢走,这对程序员来说似乎很残忍;-)
-
运算符
-
“早期人们滥用运算符重载”——尤其是标准委员会,使用 auto_ptr。
-
@SteveJessop:有人对我可以参考的“Google 风格指南”进行了深入分析。在他们对 C++ 的建议中显示什么是好/坏/丑的东西。