开发者

How to properly assign a value to the member of a struct that has a class data type?

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开发者_Python百科 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.


The problem is coming from these two lines:

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

which is not doing as you intended them to be doing. That is, these statements do not initialize foo1 and foo2 static members from the class CBar, rather they define global variables with name foo1 and foo2!

All you need to write:

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

Have you noticed the difference? Yes, you need to qualify "foo1" and "foo2" with CBar.

However, I would prefer to write:

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

which is exactly same!


Another problem is this line:

CFoo( int v ) : m_val = v {}

which is wrong. You cannot use "=" in the initialization-list. Write this:

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

Now your code should work! :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜