简体   繁体   English

为什么在定义类之前声明它的对象会在友元类中产生错误而在友元函数中不会产生错误

[英]why declaring an object of a class before defining it gives error in friend class but not in friend function

class B;
class A {
private:
  int numA;
public:
  A(): numA(12) { }
  // friend function declaration
  friend int add(A, B);
  };

this does not give any error on declaring object of class B in friend function,,but this gives,,as firstly class B is declared 这对于在友元函数中声明B类对象没有任何错误,但是这给出了,因为首先声明了B类

 class Apple;
 class B {
 private:
 int b;

public:
void showA(Apple d)
{
    // Since B is friend of A, it can access
    // private members of A
    cout << "A::a=" ;
}
};
};

this gives an error of incomplete type for object d,,why this is happening though we already declared class apple before, 这给对象d的类型不完整的错误,为什么会发生这种情况虽然我们之前已经声明了类apple,

Why does the first example compile? 为什么第一个例子编译?

In your first example, you have a forward declaration of class B followed by a declaration of a friend function that uses it in its parameter list: 在第一个示例中,您有一个class B前向声明 ,后面跟一个在其参数列表中使用它的友元函数的声明

class B;
class A {
  ...
  friend int add(A, B);
};

This is allowed because, although B is incomplete, we are not defining add yet, only declaring an intention to eventually do so. 这是允许的,因为尽管B不完整,但我们还没有定义add ,只是声明最终这样做的意图。

Why does the second example not compile? 为什么第二个例子没有编译?

In the second example, we have a forward declaration of class Apple , followed by a definition of showA : 在第二个例子中,我们有class Apple的前向声明,后面是showA定义

class Apple;
class B {
  ...
  void showA(Apple d)
  {
    ...
  }
};

This time, since we are defining the function, the compiler is obligated to generate code for it. 这一次,由于我们定义了函数,编译器有义务为它生成代码。 But because Apple is incomplete, the compiler cannot know, for example, how much space in memory to reserve to hold the parameter d . 但由于Apple不完整,编译器无法知道,例如,内存中要保留多少空间来保存参数d Therefore this is an error. 因此这是一个错误。

The question When can I use a forward declaration? 问题我何时可以使用前瞻性声明? explains some of what can and cannot be done with an incomplete (forward-declared) type. 解释了一些不完整(前向声明)类型可以做什么和不可以做什么。

The use of 'friend' is irrelevant here 在这里使用'朋友'是无关紧要的

The friend keyword is basically irrelevant here. friend关键字在这里基本上无关紧要。 friend primarily affects access control (in the sense of public and private ), but that's not the issue here. friend主要影响访问控制(在publicprivate的意义上),但这不是问题。

A detail: friend also affects scoping. 细节: friend也会影响范围。 Because of friend , add is not a member of class A , but rather refers to a member of the global scope without actually introducing one (it's weird). 因为friendadd不是class A的成员,而是指的是全局范围的成员而不实际引入一个 (这很奇怪)。 But that does not change whether an incomplete type can be used as a parameter. 但这不会改变是否可以将不完整类型用作参数。

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

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