这个typedef的意思是什么

What is the meaning of this typedef?

本文关键字:意思是 是什么 意思 typedef 这个      更新时间:2023-10-16

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"的含义是什么?

在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 s:的正常指针

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