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

时间:2013-02-07 13:10:00

标签: c++ iostream

我写了一些我学到的基本代码,可以用来定义一个类型,它获取一个枚举值作为构造函数参数,并有一个成员函数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;
}

2 个答案:

答案 0 :(得分:7)

您不需要<iostream><string>需要std::string,您可能通过<iostream>间接获得{{1}}。

答案 1 :(得分:5)

您不需要包含<iostream>,而是<string>,因为您使用std::string,因此可能会关闭编译器。

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

相关问题