How to properly assign a value to the member of a struct that has a class data type?
Posted
by
sasayins
on Stack Overflow
See other posts from Stack Overflow
or by sasayins
Published on 2011-01-13T05:39:29Z
Indexed on
2011/01/13
6:53 UTC
Read the original article
Hit count: 186
c++
Hi,
Please kindly see below for the codes. Its compiling successfully but the expected result is not working. Im very confused because my initialization of the array is valid,
//cbar.h
class CBar
{
public:
class CFoo
{
public:
CFoo( int v ) : m_val = v {}
int GetVal() { return m_val; }
private:
int m_val;
};
public:
static const CFoo foo1;
static const CFoo foo2;
public:
CBar( CFoo foo ) m_barval( foo.GetVal() ){}
int GetFooVal() { return m_barval; }
private:
int m_barval;
};
//cbar.cpp
const CBar::CFoo foo1 = CBar::CFoo(2);
const CBar::CFoo foo2 = CBar::CFoo(3);
//main.cpp
struct St
{
CBar::CFoo foo;
};
St st[] = { CBar::foo1, CBar::foo2 };
for( int i=0; i<sizeof(st)/sizeof(St); i++ )
{
CBar cbar( st[i].foo );
std::cout << cbar.GetFooVal() << std::endl;
}
But then when I change the St::foo to a pointer. And like assign the address of CBar::foo1 or CBar::foo2, its working, like this,
//main.cpp
struct St
{
const CBar::CFoo *foo;
};
St st[] = { &CBar::foo1, &CBar::foo2 };
for( int i=0; i<sizeof(st)/sizeof(St); i++ )
{
CBar cbar( *st[i].foo );
std::cout << cbar.GetFooVal() << std::endl;
}
The real problem is. The app should output
2
3
Please advice.
Many thanks.
© Stack Overflow or respective owner