cuba
cuba

Reputation: 1

error for forward declaration of class before usage in a map

I am a beginner in c++. I am not much aware about the the usage of maps or other stl containers. In my program I have defined one class group and one map<int,group>mymap

Its a very long code and most of it is irrelevant so i am giving a small part of it which is as follows:

map<int, group>idgroup;
class group;    //forward reference

class user
{
private:
  int w;
  int d;
  float p;
public:
  int present_gid;
  friend void calcprice(int*, int);

}c[50];

class group
{
  private:
  int g_id;
  int td;

public:
  vector<int>members;
  group* next;

  group()
  {
    td = 0;
    next = NULL;
  }
}

void calcp(int* id, int n)
{
  int gid,Td;
  float p=0.01,q=0.1,r=8,cpu;
  for(int i=0; i<n; i++)
  {
    gid = c[id[i]].present_gid;
    group g = idgroup.find(gid)->second;
    Td = g.td;
    cpu = (p*pow(Td,2) + q*Td + r)/Td;
    c[id[i]].p = cpu*c[id[i]].d;
  }
}

int main()
{
  int n;
  cin>>n;
  int *grp_id = new int[n];
  calcp(grp_id, n);
  return 0;
}

When I give the map declaration before the class I get the following error:

error:‘group’ was not declared in this scope map<int, group>mymap;

and when I give a forward declaration of the class, I get the following error:

error: forward declaration of ‘class group’ class group;

I am not able to understand what is the problem. Please help. Thank you!

Upvotes: 0

Views: 770

Answers (1)

Doonyx
Doonyx

Reputation: 590

I think you have to solutions depending on the context.

  1. Keep forward declaration for group class as is, and declare your mymap like std::map < int, group *>. Having a pointer type would be problematic in your code. Depends on the context.

  2. Remove forward declaration and include the header file which contains the declaration of class group. It seems this may be a fair solutions for you. Again depends on the context. If have to hide header file inclusion to optimize compile time efficiency. This is not suitable.

Upvotes: 1

Related Questions