繁体   English   中英

如何正确地将值赋给具有类数据类型的结构的成员?

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

请在下面查看代码。 它编译成功但预期结果不起作用。 我很困惑,因为我的数组初始化是有效的,

//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;
}

但是当我将St :: foo更改为指针时。 并且像分配CBar :: foo1或CBar :: foo2的地址一样,它的工作方式如此,

//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;
}

真正的问题是。 该应用程序应输出

2
3

请指教。

非常感谢。

问题来自这两条线:

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

这并不像你打算做的那样。 也就是说,这些语句不会从类CBar初始化foo1和foo2静态成员,而是定义名为foo1和foo2的全局变量!

所有你需要写的:

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

你注意到了区别吗? 是的,你需要用CBar来限定“foo1”和“foo2”。

但是,我更愿意写:

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

这完全一样!


另一个问题是这一行:

CFoo( int v ) : m_val = v {}

这是错的。 您不能在初始化列表中使用“=”。 写这个:

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

现在你的代码应该工作了! :-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM