引用基类时需要一个命名空间 [英] Is a namespace required when referring to the base class

查看:118
本文介绍了引用基类时需要一个命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

namespace N {
   class B {
     public:
       virtual void doStuff(B *) = 0;
    };
 }

 // not in a namespace
 class Derived : public N::B {
   public:
       void doStuff(B *); // Should this be N::B, or is B ok?
 };

我需要命名空间限定符,Derived引用它的基类吗? GCC和MSVC对编写的代码感到满意,但另一个编译器抱怨,除非我把命名空间放在中。C ++标准说什么?

Do I need the namespace qualifier where Derived refers to it's base class? GCC and MSVC are happy with the code as written, but another compiler complains unless I put the namespace in. What does the C++ standard say?

推荐答案

在类定义B内部是OK的。这是所谓的 注入的类名

Inside the class definition B is OK. That's the so-called injected class name.

这也是指模板例如

template <class T> class B{};
template <class T> class C: public B<int>
{
   void f(B* p) {} //same as B<int>* p
   void f(C* p) {} //same as C<T>* p
};

一般来说,基类(和类本身)或模板参数。

In general the base class (and the class itself) can be referred to inside the class definition without qualification or template arguments.

来自标准的引用:


-name插入到在看到class-name之后立即声明的范围中。类名也是
插入到类本身的范围内;这被称为
inject-class-name。为了访问检查,
inject-class-name被视为公共成员名。

9.2 : A class-name is inserted into the scope in which it is declared immediately after the class-name is seen. The class-name is also inserted into the scope of the class itself; this is known as the injected-class-name. For purposes of access checking, the injected-class-name is treated as if it were a public member name.

从这个定义可以看出,类本身的名称可以从类中公开访问,因此在派生类中可用。这证明了我的观点,B和N :: B是一样的,因为名字B是继承的

From this definition it follows that the name of the class itself is publicly accessible from the class, and therefore is available in derived classes. Which proves my point about B being OK along with N::B because the name B is inherited

Btw,这也解释了为什么以下是无效的:

Btw, this also explains why the following is invalid:

template <class T> class B{};
template <class T> class C: public B<T>
{
     voiid f(B* p){} //ERROR
    // the above is invalid!! Base class is dependent therefore 
    //its scope is not considered during unqualified name lookup
     void g(typename C::B* p){} //this is valid, same as B<T>* p  
};

14.6.1在模板中讲述注入的类名。这太粘了这里太长了。
Hth

14.6.1 Speaks about injected class names in templates. It is far too long to paste here. Hth

这篇关于引用基类时需要一个命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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