简体   繁体   English

C ++中的朋友声明

[英]friend declaration in C++

In Thinking in C++ by Bruce eckel, there is an example given regarding friend functions as 在Bruce eckel的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;
}

Now he explained this: 现在他解释了这个:

Notice that Y::f(X*) takes the address of an X object. 请注意,Y :: f(X *)获取X对象的地址。 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). 但是,如果尝试传递整个对象,编译器必须先查看X的整个结构定义,以了解大小以及如何传递它,然后才能声明Y :: g(X)等函数。

But when I tried 但是当我尝试的时候

void f(X);  

as declaration in struct Y, it shows no error. 作为struct Y中的声明,它没有显示错误。 Please explain why? 请解释原因?

It should be fine to pass the incomplete object X by value, though during the function implementation the complete type X must be available irrespective of whether the object of type X is actually used in function or not. 通过值传递不完整对象X应该没问题,但是在函数实现期间,无论X类型的对象是否实际在函数中使用,完整类型X必须是可用的。 A function declaration is all fine with incomplete object as argument or return type, except covariant return type (for member function) where such return type must be complete type. 函数声明对于不完整的对象作为参数或返回类型都是正常的,除了协变返回类型(对于成员函数),其中此类返回类型必须是完整类型。

The parameter types for function declarations may be incomplete. 函数声明的参数类型可能不完整。

For data member declarations and all definitions however, the type has to be complete: 但是,对于数据成员声明和所有定义 ,类型必须是完整的:

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

The problems is when you change the declaration in struct X. 问题是当您更改struct X中的声明时。

So, inside struct X you tell the compiler the struct has a function which receives something of type X, but wait a minute, type X is not fully define at this point! 所以,在struct X中你告诉编译器struct有一个函数接收类型为X的东西,但是等一下,类型X在这一点上还没有完全定义!

You can't use an incomplete type as a parameter for function f but you can use the address of an incomplete type, thus X*. 您不能将不完整类型用作函数f的参数,但可以使用不完整类型的地址,即X *。

On a site note, it will be very important for you to increase your acceptance rate so you get answers for your future questions and important for my ego if i got the right answer :) 在网站上注意,提高你的录取率对你来说非常重要,这样你就可以得到未来问题的答案,如果我得到了正确的答案,那对我的自我很重要:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM