3

When compiling this code on VS2008:

  #include <vector>

using namespace std;

class Vertex {

public: double X; 
        double Y;
        double Z;

        int id; // place of vertex in original mesh vertex list

        vector<Vertex*> neighbor; //adjacent vertices

        vector<Triangle*> face; // adjacent triangles

        float cost; // saved cost of collapsing edge

        Vertex *collapse; // 
};



 class Triangle {

public:
    Vertex * vertex[3]; 


};

I get the following error:

1>.\Triangle.cpp(15) : error C2065: 'Triangle' : undeclared identifier 

How can I fix this?

Dima
  • 38,860
  • 14
  • 75
  • 115
andandandand
  • 21,946
  • 60
  • 170
  • 271

2 Answers2

6

You use a forward declaration:

class Traingle;

class Vertex
{
    ...
};

class Triangle
{
    ...
};

A forward declaration of a type (e. g. class Triangle) allows you to declare pointers or references to that type, but not objects of the type. In other words

class Triangle;
class Vertex
{
  vector<Triangle*> face;
};

will compile, but

class Triangle;
class Vertex
{
  vector<Triangle> face;
};

will not compile.

Also, a forward declaration of a type does not let you access its members, because the compiler does not know about them yet. So the member functions that use objects of the forward declared type must be defined after the type is fully defined. In your case, after the definition of class Triangle.

Oh, and this is not at all specific to Visual Studio. This is just standard C++.

Dima
  • 38,860
  • 14
  • 75
  • 115
  • 1
    Usually I like to use forward declarations in my header files and then include everything in the .cpp files so that when I change something in a header file that's included by other files, only the .cpps will recompile. – Jordan Nov 11 '11 at 20:03
  • @Jordan: absolutely correct. I didn't mention it because I thought it was a bit outside the scope of the question. – Dima Nov 11 '11 at 20:12
2

You need to forward declare the Triangle class before the Vertex class. In this case that would look something like this:

#include <vector>

using namespace std;

class Triangle;

class Vertex {
public:
        double X; 
        double Y;
        double Z;

        int id; // place of vertex in original mesh vertex list

        vector<Vertex*> neighbor; //adjacent vertices
        vector<Triangle*> face; // adjacent triangles
        float cost; // saved cost of collapsing edge

        Vertex *collapse; // 
};

class Triangle {
public:
    Vertex * vertex[3]; 
};

This previous question seems to contain good details about forward declaration.

Community
  • 1
  • 1