'[Class name]' does not name a type in C++

99封情书 提交于 2019-12-30 07:24:09

问题


I am programming a graph using a list of lists. For that, I have two classes, and each one of this classes has a pointer to another object of the same class and a pointer to the object of the second class. Here is the code:

File V.h:

#ifndef VERTICEPUNT_H
#define VERTICEPUNT_H

#include "A.cpp"

typedef char E;

 class V
{
    public:
    E etiqueta;
    V* siguiente;
    A* primera;  //<- Error: 'A' does not name a type

    V();
    ~V();
};

#endif // VERTICEPUNT_H

File V.cpp:

#include "V.h"

 V::V()
{
     etiqueta = ' ';
     siguiente = 0;
     primera = 0;  //<- Error: 'primera' was not declared in this scope
}

 V::~V()
{
    delete primera;
    delete siguiente;
}

File A.h:

#ifndef ARISTAPUNT_H
#define ARISTAPUNT_H

#include "V.cpp"

typedef int P;

 class A
{
    public:
        P peso;
        V* vertice;
        A* siguiente;

         A();
        ~A();
};

 #endif // ARISTAPUNT_H

A.cpp:

#include "A.h"

 A::A()  //<- Error: 'A' does not name a type
{
     peso = 0;
     siguiente = 0;
     vertice = 0;
}

 A::~A()  // <- Error: 'A' does not name a type
{
    delete siguiente;
}

How would I be able to fix that?


回答1:


The message means that the class name is not in scope. V.h should not include A.cpp, it should include A.h. Same goes for A.h inclusion of V.cpp.

In general, you never want to #include a CPP file - from a header or from another CPP file. Only .h header files are designed for inclusion by preprocessor.

In case of circular definitions like this, you should forward-declare the class the pointer to which you are defining, and forego inclusion of that class's header:

#ifndef VERTICEPUNT_H
#define VERTICEPUNT_H

class A; // <<== Forward declare the class.

typedef char E;

 class V
{
    public:
    E etiqueta;
    V* siguiente;
    A* primera;

    V();
    ~V();
};

#endif // VERTICEPUNT_H


来源:https://stackoverflow.com/questions/17333934/class-name-does-not-name-a-type-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!