【发布时间】:2013-02-22 22:37:25
【问题描述】:
我有一个使用std::string 的小类widget。它在许多地方使用它,通常与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)和(3)的地方,它与1 中的情况相同。只是命名空间example和example::nested将在包含widget.h的第二个文件中被污染? - 在
(4)和(5)的地方,声明是相当孤立的,但它会在实现 (Cpp) 文件和继承类中可见吗?
提前致谢!
【问题讨论】:
-
我认为这取决于你到底想要什么。我想最好的放置位置是您只需要使用它的地方。如果你只想在课堂上使用它,那么 4 和 5 是合理的。
-
虽然位置 4 和 5 似乎是完美的选择,但我无法让 g++ 接受 - 我得到
using-declaration for non-member at class scope。 -
但是
using base_class::shadowed_function有效吗?
标签: c++ namespaces using