Please see below codes. Its compilation is successful, but the expected result does not work. I am very confused because my array initialization is valid,
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;
};
const CBar::CFoo foo1 = CBar::CFoo(2);
const CBar::CFoo foo2 = CBar::CFoo(3);
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 St :: foo to a pointer. And how to assign the address CBar :: foo1 or CBar :: foo2, its work, for example,
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. The application should output
2
3
Please advice.
Many thanks.
source
share