我目前使用以下Perl来检查变量是否已定义并包含文本.我必须首先检查defined
以避免"未初始化的值"警告:
if (defined $name && length $name > 0) {
# do something with $name
}
Run Code Online (Sandbox Code Playgroud)
写这个有更好的(可能是更简洁的)方法吗?
在以下C++函数中:
void MyFunction(int age, House &purchased_house)
{
...
}
void MyFunction(const int age, House &purchased_house)
{
...
}
Run Code Online (Sandbox Code Playgroud)
哪个更好?
在两者中,'年龄'都是按价值传递的.我想知道'const'关键字是否有必要:对我来说似乎是多余的,但也很有用(作为额外的指示,变量不会改变).
有没有人对上述哪个(如果有的话)更好有任何意见?
在Perl中,哪些是"更好"的风格?
$hash{"string"} or $hash{string}?
Run Code Online (Sandbox Code Playgroud)
无论如何,它们的功能是否相同?
我正在读一本书来学习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();
Run Code Online (Sandbox Code Playgroud)
我正在尝试的部分是使用运算符<来允许列表自行排序.
这一切似乎都很好,但http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Operator_Overloading似乎建议避免这样做,这正是本书所说的!("特别是,不要重载operator ==或operator <只是为了让你的类可以用作STL容器中的键;相反,你应该在声明容器时创建相等和比较functor类型.")
我理解"创建相等和比较函子类型"意味着创建比较函数,如下所示:
bool my_comparison_function(const CatalogueItem &a, const CatalogueItem &b)
{
// my comparison code here
}
Run Code Online (Sandbox Code Playgroud)
风格指南是指什么?
有没有人可以选择哪种方法更"正确"?
Ĵ
我正在尝试使用std :: set和类进行组合,如下所示:
#include <set>
class cmdline
{
public:
cmdline();
~cmdline();
private:
set<int> flags; // this is line 14
};
Run Code Online (Sandbox Code Playgroud)
但是,它不喜欢设置标志; 部分:
cmdline.hpp:14: error: ISO C++ forbids declaration of 'set' with no type
cmdline.hpp:14: error: expected ';' before '<' token
make: *** [cmdline.o] Error 1
Run Code Online (Sandbox Code Playgroud)
据我所知,我给了一个类型(int).你是否以不同的方式编写"set variable"行,或者它是否不允许?