必须在声明朋友时声明类键 [英] a class-key must be declared when declaring a friend

查看:159
本文介绍了必须在声明朋友时声明类键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我声明一个朋友时,g ++编译器抱怨这个错误:

The g++ compiler complains with this error when I declare a friend thusly:

friend MyClass;

而不是

friend class MyClass;

为什么需要 class 关键字?
(Borland C ++编译器,BTW,不需要它。)

Why should the class keyword be required? (the Borland C++ compiler, BTW, does not require it.)

无法编译器在符号表中查找MyClass,被声明为类? (它显然是在做查找反正,因为它抱怨当MyClass它没有声明)

Couldn't the compiler simply look-up MyClass in the symbol table and tell it was declared as a class? (it is obviously doing the look-up anyway because it complains when MyClass it not declared)

这不是它正在做一个类的前向声明:我仍然

It is not like it is making a forward declaration of the class: I still have to have either declared the class above or at least have forward declared it.

这对我来说是有意义的(如果

It would make sense to me (would be great actually) if

friend class MyClass;

进行向前声明,否则就像对我来说似乎是语法错误。

makes a forward declaration if needed, otherwise it just seems like syntactic salt to me.

我一直在使用朋友语句,而没有没有编译器投诉的 struct 关键字近20年。
这是新东西吗?

I have been merrily using friend statements without the class or struct keyword with no compiler complaints for almost 20 years. Is this something fairly new?

推荐答案

我对此感到惊讶(因此删除了以前的错误答案)。 C ++ 03标准在11.4中说:

I was surprised about this (and as a result deleted a previous incorrect answer). The C++03 standard says in 11.4:


在类的朋友声明中应使用详细说明类型说明符。 / p>

An elaborated-type-specifier shall be used in a friend declaration for a class.

然后为了确保没有误解,它脚注:

Then to make sure there's no misunderstanding, it footnotes that with:


必须有详细说明类型说明符的类键。

The class-key of the elaborated-type-specifier is required.

GCC是唯一的编译器我有抱怨缺少类键,但它看起来像其他编译器正在让我们摆脱非标准的东西...

GCC is the only compiler that I have that complains about the missing class-key, but it looks like other compilers are letting us get away with something non-standard...

现在为理由 - 你必须问一个比我更了解编译器(或标准)的人。

Now as for the rationale - you'd have to ask someone who knows more about compilers (or standards) than I do.

这篇关于必须在声明朋友时声明类键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆