请参阅下面的代码。它编译成功但预期的结果不起作用。我很困惑,因为我对数组的初始化是有效的,
//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) {}
现在您的代码应该可以工作了! :-)
关于c++ - 如何正确地为具有类数据类型的结构成员赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4677136/