How to assign a value to a member of a structure that has a class data type?

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,

//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 St :: foo to a pointer. And how to assign the address CBar :: foo1 or CBar :: foo2, its work, for example,

//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. The application should output

2
3

Please advice.

Many thanks.

+3
source share
1 answer

The problem comes from these two lines:

const CBar::CFoo foo1 = CBar::CFoo(2);
const CBar::CFoo foo2 = CBar::CFoo(3);

which does not work as you expected. That is, these statements do not initialize the static members foo1 and foo2 from the class CBar, instead they define global variables named foo1 and foo2!

, :

const CBar::CFoo CBar::foo1 = CBar::CFoo(2);
const CBar::CFoo CBar::foo2 = CBar::CFoo(3);

? , "foo1" "foo2" CBar.

:

const CBar::CFoo CBar::foo1(2);
const CBar::CFoo CBar::foo2(3);

!


:

CFoo( int v ) : m_val = v {}

. "=" . :

CFoo( int v ) : m_val(v) {}

!: -)

+8

Source: https://habr.com/ru/post/1785130/


All Articles