gpt4 book ai didi

c++ - C++ 友元声明

转载 作者:太空狗 更新时间:2023-10-29 22:53:15 24 4
gpt4 key购买 nike

在 Bruce eckel 的 Thinking in C++ 中,给出了一个关于友元函数的例子

// Declaration (incomplete type specification):
struct X;
struct Y {
void f(X*);
};
struct X { // Definition
private:
int i;
public:
friend void Y::f(X*); // Struct member friend
};
void Y::f(X* x) {
x->i = 47;
}

现在他解释了这个:

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. If you try to pass the whole object, however, the compiler must see the entire structure definition of X, to know the size and how to pass it, before it allows you to declare a function such as Y::g(X).

但当我尝试过

void f(X);  

作为struct Y中的声明,它没有显示错误。请说明原因?

最佳答案

函数声明的参数类型可能不完整。

然而,对于数据成员声明和所有定义,类型必须是完整的:

struct A;
struct B {
void f(A); // declaration, fine
void g(A) {} // error
A a; // error
};

关于c++ - C++ 友元声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2767576/

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