gpt4 book ai didi

c++ - 在头文件中使用 std

转载 作者:太空宇宙 更新时间:2023-11-04 16:02:09 24 4
gpt4 key购买 nike

是否有任何选项可以在不使用任何#include 语句的情况下在头文件中使用 std?我在头文件中有一个类如下;

class Sequence{
private:
std::string sequence;
unsigned length;
public:
/* Constructors */
Sequence (void);
Sequence (std::string, unsigned);
Sequence (const Sequence &);

/* Destructor Definition */
~Sequence(){}

/* Overloaded Assignment */
Sequence & operator
= (const Sequence &seq)
{
sequence = seq.sequence;
length = seq.length;
return *this;
}

/* Setter and Getter Functions */
void setSequence(std::string);
void setLength(unsigned);
std::string getSequence(void);
int getLength(void);
};

如果不包含 iostream,则无法正确编译。但是,我在相关问题中阅读了一些评论,其中我们不应在头文件中包含库和其他头文件。那么呢?

最佳答案

如果在您自己的 header A 中,您依赖于来自另一个 header B(无论是标准 header 还是其他 header )的类型定义或函数声明,那么您必须在 header A 中包含 header B。

一般来说,你无法避免它。在某些情况下,您可能只依赖于一个类型的声明,在这种情况下,您可以通过使用前向声明来避免包含定义。但是,这不适用于标准库中的类型,因为它们位于您不能声明任何内容的命名空间中。

It is not compiled correctly without including iostream

实际上,您的类定义取决于 <string> .有可能<iostream>包括 <string> ,但你不能依赖它。包括<string>相反,因为您使用了在那里定义的类型 ( std::string )。

we should not include libraries AND another header files in a header file.

您必须包括您依赖的所有 header ,无论它们是否来自库。包含库 header 和其他 header 没有任何问题。

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

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