gpt4 book ai didi

c++ - 这个typedef是什么意思?

转载 作者:可可西里 更新时间:2023-11-01 18:20:58 25 4
gpt4 key购买 nike

在 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”是什么意思?

最佳答案

In Mr Kenny Kerr's this column, he defined a struct and a typedef like this:

struct boolean_struct { int member; };    
typedef int boolean_struct::* boolean_type;

Then what is the meaning of this 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;
}

如您所见,语法和它们的行为是不同的。

Another question is concerning the following code:

operator boolean_type() const throw()
{
return Traits::invalid() != m_value ? &boolean_struct::member : nullptr;
}

What is the meaning of "&boolean_struct::member" ?

这将返回 boolean_struct 中的 member 变量的地址。参见上面的代码示例。

关于c++ - 这个typedef是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9732145/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com