在Kenny Kerr先生的this column中,他定义了一个结构和类似于这样的typedef:
struct boolean_struct { int member; };
typedef int boolean_struct::* boolean_type;
那么这个typedef是什么意思?
另一个问题是关于以下代码:
operator boolean_type() const throw()
{
return Traits::invalid() != m_value ? &boolean_struct::member : nullptr;
}
“& boolean_struct :: member”是什么意思?
答案 0 :(得分:13)
在Kenny Kerr先生的本专栏中,他定义了一个struct和一个typedef 这样:
struct boolean_struct { int member; }; typedef int boolean_struct::* boolean_type;
那么这个typedef是什么意思?
typedef
创建一个名为boolean_type
的类型,它相当于指向int
对象中boolean_struct
成员的指针。
指向int
的指针 不一样。区别在于boolean_type
的对象需要boolean_struct
个对象才能取消引用它。指向int
的普通指针不会。查看其不同之处的最佳方法是通过一些代码示例。
仅考虑int
的正常指针:
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;
}
现在考虑我们是否使用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;
}
如您所见,语法及其行为是不同的。
另一个问题是关于以下代码:
operator boolean_type() const throw() { return Traits::invalid() != m_value ? &boolean_struct::member : nullptr; }
“& boolean_struct :: member”是什么意思?
这将返回member
内boolean_struct
变量的地址。见上面的代码示例。