【问题标题】:C++/multiple files with vector of object pointers带有对象指针向量的 C++/多个文件
【发布时间】:2010-12-18 21:14:33
【问题描述】:

通过查看下面的代码,这个问题的基本思想应该是有意义的,但我会尝试解释。基本上我有两个通过指针相互引用的类,然后这些类位于两个单独的头文件中。该程序仅在没有将 b 类型指针的向量添加到 A.h 中的部分的情况下工作。

#include <iostream>  
#include "A.h"  
#include "B.h"  

using namespace std;  
class a;  
class b;  

int main()  
{  
    a* oba = new a;  
    b* obb = new b;  

    oba->set(obb,9);  
    obb->set(oba,0);  


    cout<<oba->get()<<endl;  
    cout<<obb->get()<<endl;  
    delete obb;  
    delete oba;  

    return 0;  
}  

//This is the A.h, look for the comment in the code where the error occurred.

#ifndef _A  
#define _A  

#include "B.h"  
#include <vector>  

class b;  

class a  
{  
    private:  
        b* objb;  
        int data;  
        vector <b*> vecb;//this is not well liked by the compiler???  

    public:  

    void set(b* temp, int value);  
    int get();  
};  
void a::set(b* temp, int value)  
{  
    objb = temp;  
    data = value;  
}  
int a::get()  
{  
    return data;  
}  
#endif  



#ifndef _B  
#define _B  

#include "A.h"  
class a;  

class b  
{  
    private:  
        a* obja;  
        int data;  

    public:  
    void set(a* temp, int value);  
    int get();   
};  
void b::set(a* temp, int value)  
{    
    obja = temp;  
    data = value;  
}  
int b::get()    
{  
    return data;   
}  
#endif  

【问题讨论】:

  • 编译器给你的错误是什么?
  • 您好,我只是将其拆分为 3 个文件并在 VS2010 上构建,没有任何问题。你能告诉我们实际的错误是什么以及你使用的是什么编译器吗?谢谢。
  • 没关系。我正在使用代码块,我猜它是 g++,但我在 A.h 中添加了“使用命名空间 std”并且它起作用了。
  • 错误:ISO C++ 禁止声明没有类型的“向量”
  • 所以我添加了 std::vector vecb;它有效吗?可以吗?

标签: c++ pointers file object vector


【解决方案1】:

用 std 命名空间限定向量。

class a
{
    ...
    std::vector<b*> vecb;
};

【讨论】:

    【解决方案2】:

    你不应该在你的B.h 中使用#include "A.h",反之亦然,否则你会得到循环依赖。

    尝试以下方法:

    (A.h)

    class B; // forward declaration
    class A
    {
        B* pb;
        ...
    }
    

    (A.cpp)

    #include "A.h"
    #include "B.h"
    ...
    

    (B.h)

    class A; // forward declaration
    class B
    {
        A* pa;
        ...
    }
    

    (B.cpp)

    #include "A.h"
    #include "B.h"
    ...
    

    HTH。

    【讨论】:

    • 请看我下面的代码。我再次收到此错误。错误:ISO C++ 禁止声明没有类型的“向量”|
    【解决方案3】:

    我在第一次发布的代码中添加了std::vector &lt;b*&gt; vecb;,它编译得很好。

    【讨论】:

      猜你喜欢
      • 2020-06-27
      • 1970-01-01
      • 2011-10-01
      • 2011-02-11
      • 1970-01-01
      • 2010-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多