这个typedef是什么意思?

7
在 Kenny Kerr 先生的这篇文章中,他定义了一个结构体和一个类似于以下的 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" 的含义是什么?
1个回答

13
在Kenny Kerr先生的这篇文章中,他定义了一个结构体和一个typedef,如下所示:
struct boolean_struct { int member; };    
typedef int boolean_struct::* boolean_type;    
那么这个typedef的含义是什么?

typedef 创建了一个名为 boolean_type 的类型,它等同于指向 boolean_struct 对象内的 int 成员的指针。

它与指向 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;
}

现在考虑如果我们在boolean_struct内使用指向int成员的指针:

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 变量的地址。请参见上面的代码示例。

谢谢你的回答。但是boolean_struct没有对象,那么&boolean_struct::member指向什么? - Rong
1
@Rong:它指向的是编译器的实现细节。通常它被实现为类成员的某种整数偏移量。但它的确切数值是无关紧要的;重要的是它允许您访问某种类型对象的特定部分,而不考虑该类型的特定实例。就像我指着人体上的一条肢体一样;我可以这样做,而不用考虑个体。这就是为什么表达式 boolean_struct::member 起作用的原因;我可以指向 boolean_struct 内部的 member,而不考虑具体的实例。 - In silico

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接