[英]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 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. 但是当我将St :: foo更改为指针时。 And like assign the address of CBar::foo1 or CBar::foo2, its working, like this,
并且像分配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;
}
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! 也就是说,这些语句不会从类
CBar
初始化foo1和foo2静态成员,而是定义名为foo1和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
. 是的,你需要用
CBar
来限定“foo1”和“foo2”。
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! 现在你的代码应该工作了! :-)
:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.