Oct 16, 2012 at 11:32pm Oct 16, 2012 at 11:32pm UTC
Hello,
I am trying to set a class object as a member of another class but I am missing something. When I declare my object as global it works fine. Here is an example of my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#include <iostream>
class Print
{
public :
Print(){}
~Print(){}
void PrintInt( int a_Data )
{
std::cout << a_Data << std::endl;
}
};
//Print a;
class Data
{
public :
Data(){}
Data(int a_Data)
{
m_Data = a_Data;
}
~Data(){}
void Print()
{
a.PrintInt(m_Data);
}
private :
int m_Data;
static Print a;
};
int main()
{
Data b(5);
b.Print();
return 0;
}
Last edited on Oct 16, 2012 at 11:34pm Oct 16, 2012 at 11:34pm UTC
Oct 16, 2012 at 11:47pm Oct 16, 2012 at 11:47pm UTC
You have a function named Print at line 23.
When you declare a at line 29 you're referencing Print.
Are you referring to the class or the function?
I changed lines 23 and 35 to PrintIt and it compiled without a problem.
Oct 16, 2012 at 11:51pm Oct 16, 2012 at 11:51pm UTC
You shall define the static member before main. For example
Print Data::a;
Oct 17, 2012 at 12:11am Oct 17, 2012 at 12:11am UTC
@vlad from moscow: I would prefer to have the Print object as a member of class Data.
@AbstractionAnon: When you say that you changed line 23 do you mean like this?
1 2 3 4
void PrintInt()
{
a.PrintInt(m_Data);
}
because it seems strange and I get errors.
Last edited on Oct 17, 2012 at 12:11am Oct 17, 2012 at 12:11am UTC
Oct 17, 2012 at 12:23am Oct 17, 2012 at 12:23am UTC
It is a static member so it should be defined as I showed. Inside the class it is a declaration not the definition of the object.
Oct 17, 2012 at 1:06am Oct 17, 2012 at 1:06am UTC
Should I still declare it in the class as static Print a;
?