为什么我的代码需要<iostream>?

Why does my code need <iostream>?

本文关键字:iostream gt 我的 lt 为什么 代码      更新时间:2023-10-16

我编写了一些我学到的基本代码,可用于定义一个类型,该类型获取枚举值作为其构造函数参数,并具有一个以字符串形式返回值的成员函数AsString()

除非我包含<iostream>,否则代码无法编译。它main显示一条警告,指出尚未声明类型 color。为什么需要在我的代码中包含输入/输出头文件,而其中没有使用输入/输出函数或运算符?

enum ColorEnum {blue, red};
class color
{
    protected:
        ColorEnum value;
    public:
        color(ColorEnum initvalue)
        {
            value = initvalue;
        }
        std::string AsString()
        {
            switch (value)
            {
                case blue:
                    return "blue";
                case red:
                    return "red";
                default:
                    return "N/A";
            }
        }
};
int main()
{
    color mycolor = blue;
    return 0;
}

你不需要<iostream>,你需要<string>才能std::string,你可能通过<iostream>间接获得。

你不需要包含<iostream>,但<string>,因为你使用std::string,所以这可能会使编译器关闭。

如果您包含<string>但仍然收到错误,这听起来像是编译器中的错误。