gpt4 book ai didi

c++ - 使用命名空间头文件c++

转载 作者:行者123 更新时间:2023-11-28 06:15:32 26 4
gpt4 key购买 nike

我试图在我正在编写的一些代码中获得一个好的结构,但我不太确定头文件。我遇到的问题之一是:我知道我不应该在头文件中包含 namespace ,但我不知道该把它放在哪里。

考虑这个标题:

// deck.h
#pragma once
#include <vector>
#include "card.h"

using namespace std;

typedef vector<card> pile;

class deck{
public:
deck();
~deck();
void shuffle();
card takeCard();
int getSize();
private:
pile cDeck;
};

card.h 中的代码是卡片结构的定义。 typedef 是否应该在头文件中?如果是这样,我该如何避免使用 std::vector?

如有任何提示,我们将不胜感激。

最佳答案

你根本就不放。使用 std::vector 而不是 vector,只需输入 5 个额外的字符。 typedef 可以放在头文件中。

您可能已经知道,using namespace std; 在 header 中是错误的。为什么?因为所有包含您的 header 的文件都将自动use namespace std;,并且很容易陷入名称冲突,尤其是在客户可能不知道using<的大型项目中 他/她隐式使用的指令。

或者,您可以使用 namespace std; inside header 中的内联函数定义,

inline void f()
{
using namespace std;
cout << "bla" << endl;
}

或类,

class Foo
{
using namespace std;
// rest
};

这样,using 仅在其封闭范围内有效“可见”。

相关:What's the scope of the "using" declaration in C++?

关于c++ - 使用命名空间头文件c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30414907/

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