gpt4 book ai didi

c++ - Eckel Vol1,pg283,类型规范不完整,编译器在做什么?

转载 作者:行者123 更新时间:2023-11-28 00:56:06 24 4
gpt4 key购买 nike

struct X;

struct Y {
void f(X*);
};

struct X { //definition
private:
int i;
public:
friend void Y::f(X*);
<SNIP'd>
};

"struct Y has a member function f() that will modify an object of type X. This is a bit of a conundrum because the C++ compiler requires you to declare everything before you can refer to it, so struct Y must be declared before its member Y::f(X*) can be declared as a friend in struct X. But for Y::f(X*) to be declared struct X must be declared first!

Here's the solution. Notice that Y::f(X*) takes the address of an X object. This is critical because the compiler always knows how to pass an address, which is of a fixed size regardless of the object being passed, even if it doesn't have full information about the size of the type."

所以这里我们有:

struct X; struct Y { ... }; struct X { ... };

我的问题是:

  1. 为什么编译器坚持不完整地声明X:struct X;??

    毕竟,正如作者所说:“编译器总是知道如何传递一个地址这是固定大小的。”这只是一个声明,它告诉编译器 X 是一个结构并且很快就会跟进,那么为什么编译器如此坚持让您输入这些字母:struct X; 毕竟我不是在使用 X 本身吗?此时没有生成汇编语言代码。当它读取 X* 当然它可以告诉它它是一个地址(指针).. 为什么:struct X; 需要?

    声明函数的全部意义在于在实际执行之前进行类型检查用法。所以如果我这样做:

     int foo(void); foo(30); 

    然后编译器会咆哮。但是在上面,如果我不说:struct X; 有什么不同呢?他只是在检查我对 X(函数名称)的拼写吗?

  2. 为什么颠倒结构 Y 和 X 的位置不起作用?像这样:
    结构 Y;结构 X { ... };结构 Y { ... };
    我得到:

    error: invalid use of incomplete type 'struct main()::Y'

    显然,编译器对我不完整的类型规范不满意Y(struct Y;)。但是缺少什么宝贵的小信息?后所有结构 Y;应该告诉编译器 Y 很快就会跟进(与做我们在 Q1 中做了什么: struct X;结构 Y {};结构 X{}; )

  3. 为什么作者将 struct X 称为定义?如果我做:struct X { ... }; 这肯定是声明?当我实例化结构如下:X foo;那么它是一个定义?正确吗?

  4. 我该怎么做:

    struct X {
    friend void Y::f(X*);
    void f(Y*);
    };

    struct Y {
    friend void X::f(Y*);
    void f(X*);
    };

最佳答案

Why does the compiler insist that X be declared incompletely as: struct X?? After all, as the author notes: "compiler always knows how to pass an address which is of a fixed size.."

你不需要:这也行:

struct Y { void f(struct X*); };

class X {
int i;
friend void Y::f(X*);
};

您还有什么建议?

此外,当按值传递时,您甚至不必拥有完整的类型除非您实际上定义了方法:

struct Y { void f(struct X); };

// too early:
void Y::f(struct X) { /* whoops compile error */ }

class X {
int i;
friend void Y::f(X);
};

// ok here:
void Y::f(X) { /* compile success */ }

关于c++ - Eckel Vol1,pg283,类型规范不完整,编译器在做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11154679/

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