Ron*_*ong 7 c++ typedef structure
在Kenny Kerr先生的这一专栏中,他定义了一个结构和一个类似于这样的typedef:
struct boolean_struct { int member; };
typedef int boolean_struct::* boolean_type;
Run Code Online (Sandbox Code Playgroud)
那这个typedef是什么意思?
另一个问题是关于以下代码:
operator boolean_type() const throw()
{
return Traits::invalid() != m_value ? &boolean_struct::member : nullptr;
}
Run Code Online (Sandbox Code Playgroud)
"&boolean_struct :: member"是什么意思?
In *_*ico 13
在Kenny Kerr先生的这一专栏中,他定义了一个结构和一个类似于这样的typedef:
Run Code Online (Sandbox Code Playgroud)struct boolean_struct { int member; }; typedef int boolean_struct::* boolean_type;那这个typedef是什么意思?
在typedef创建一个名为类型boolean_type这相当于一个指向int一个内侧部件boolean_struct对象.
这是不是同样的事情的指针int.不同之处在于,对象boolean_type需要一个boolean_struct对象才能取消引用它.指向a的普通指针int不是.查看其不同之处的最佳方法是通过一些代码示例.
只考虑ints的正常指针:
struct boolean_struct { int member; };
int main()
{
// Two boolean_struct objects called bs1 and bs2 respectively:
boolean_struct bs1;
boolean_struct bs2;
// Initialize each to have a unique value for member:
bs1.member = 7;
bs2.member = 14;
// Obtaining a pointer to an int, which happens to be inside a boolean_struct:
int* pi1 = &(bs1.member);
// I can dereference it simply like this:
int value1 = *pi1;
// value1 now has value 7.
// Obtaining another pointer to an int, which happens to be inside
// another boolean_struct:
int* pi2 = &(bs2.member);
// Again, I can dereference it simply like this:
int value2 = *pi2;
// value2 now has value 14.
return 0;
}
Run Code Online (Sandbox Code Playgroud)
现在考虑我们是否使用了指向int成员内部成员的指针boolean_struct:
struct boolean_struct { int member; };
typedef int boolean_struct::* boolean_type;
int main()
{
// Two boolean_struct objects called bs1 and bs2 respectively:
boolean_struct bs1;
boolean_struct bs2;
// Initialize each to have a unique value for member:
bs1.member = 7;
bs2.member = 14;
// Obtaining a pointer to an int member inside a boolean_struct
boolean_type pibs = &boolean_struct::member;
// Note that in order to dereference it I need a boolean_struct object (bs1):
int value3 = bs1.*pibs;
// value3 now has value 7.
// I can use the same pibs variable to get the value of member from a
// different boolean_struct (bs2):
int value4 = bs2.*pibs;
// value4 now has value 14.
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如您所见,语法及其行为是不同的.
另一个问题是关于以下代码:
Run Code Online (Sandbox Code Playgroud)operator boolean_type() const throw() { return Traits::invalid() != m_value ? &boolean_struct::member : nullptr; }"&boolean_struct :: member"是什么意思?
这将返回membera中变量的地址boolean_struct.见上面的代码示例.