gpt4 book ai didi

c++ - using 声明应该有多窄?

转载 作者:可可西里 更新时间:2023-11-01 18:20:33 27 4
gpt4 key购买 nike

我有一个使用 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. 如果我将它放在 (1) 中,那么包含 widget.h 的每个人的作用域都会被 string 污染?
  2. (2)(3) 中,它与 1 中的故事相同。只是命名空间 exampleexample::nested 将在包含 widget.h 的第二个文件中被污染?
  3. (4)(5) 中,声明是相当孤立的,但它在实现 (Cpp) 文件和继承类中是否可见?

提前致谢!

最佳答案

在(1)中不要这样做。
每个人都会诅咒你的名字一千年。
作为您类(class)的用户,我不介意您污染自己的命名空间。但是如果你污染了我的任何命名空间(包括全局),我会很不高兴,因为这会影响我的代码的编译方式。 Why is "using namespace std" considered bad practice?

您不能在 (4) 或 (5) 处使用它。

因为我(个人)希望将它绑定(bind)到尽可能靠近使用点(以防止污染)。
你能做的最好的是 (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;

关于c++ - using 声明应该有多窄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15276125/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com