我有这个小班widget
使用一个std::string
。它在很多地方使用它,通常与std::vector
。所以你可以看到,类型名变得非常长而且烦人。
我想利用using
关键字,即using std::string;
问题是,最好放置在哪里?
// widget.h file
#ifndef WIDGET
#define WIDGET
// (1)
namespace example {
// (2)
namespace nested {
// (3)
class widget {
public:
// (4)
...
private:
// (5)
std::string name_;
...
};
}
}
#endif
我的问题是:
- 如果我把它放在
(1)
那么每个人包括widget.h
他们的范围会被污染string
?
- 在一些地方
(2)
and (3)
,与 1 中的情况相同,只是名称空间example
and example::nested
将在第二个文件中被污染,其中包括widget.h
?
- 在一些地方
(4)
and (5)
,声明是相当孤立的,但是它在实现(Cpp)文件和继承类中是否可见?
提前致谢!
不要执行(1) 中的操作。
每个人都会咒骂你的名字一千年。
作为您班级的用户,我不介意您污染自己的名称空间。但如果你污染了我的任何命名空间(包括全局命名空间),我会感到不安,因为这会影响我的代码的编译方式。为什么“使用命名空间 std”被认为是不好的做法? https://stackoverflow.com/q/1452721/14065
您不能在 (4) 或 (5) 处使用它。
因为我(个人)希望将其尽可能靠近使用点(以防止污染)。
你能做的最好的事情就是(3)。
但我什至不会那样做。我对标准中的任何事情都很明确。但我会 typedef 我的容器类型。
private: //(so at 5) Don't need to expose internal details of your class.
typedef std::vector<std::string> MyCont;
这是一种更好的技术,因为您只需要在一个地方进行更改,并且更改将会级联。
// Sub typedefs now will no longer need to change if you change
// The type of container. Just change the container typedef and
// now the iterators are automatically correct.
public: //(so at 4) Iterators are public (and not exposing the implementation).
typedef MyCont::iterator iterator;
typedef MyCont::const_iterator const_iterator;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)