如何在c ++的头文件中使用类的对象作为另一个类的数据?

时间:2014-01-15 01:41:18

标签: c++

假设我有3个文件:main.cppother.hother.cpp。 我想创建一个名为other的类,它包含一个字符串和一个vector作为数据。如果我这样写other.h

    //other.h
    #include <string>
    #include <vector>
    class other
    {
    private:
        string str;
        vector<int> v;
    public:
        /*does not need to be included for this example,
        but would include constructors and functions.*/
    };

然后我的编译器会告诉我字符串不是一个类型,即使我包含它,并且我必须指定向量的类型,即使我做了。如何在没有编译器错误的情况下在类中使用向量或字符串?

1 个答案:

答案 0 :(得分:1)

您的using namespace std;可能有main.cpp或类似内容。这样的声明允许您使用不合格的名称,如stringvector。但是,通常的做法是(标题文件中特别是)来完全限定标准库中的名称 - std::stringstd::vector

有关详细信息,请参阅问题Why is “using namespace std;” considered bad practice?