C++ - "using" 关键字说明

C++ - the "using" keyword clarification

我需要一些关于 classes 的 using 关键字的快速说明,因为我不确定我是否理解正确。

假设我有以下示例:

class B {
public:
    int var;
    int f(void);

};

class C : public B {protected: using B::var; };

这是否意味着 class C 不是从 class B 继承变量 varpublic,而是继承此变量为 protected 和剩下的唯一 public 变量将是 int f(void);?

此外,class C 是否可以通过在其主体中包含 private: using B::var; 来继承私有变量?

因为变量 var 已经 public 在 class B 中,所以写 public: using B::var; 有什么意义吗?

谢谢!

Does that mean that instead of inheriting the variable var as public from class B, class C instead inherits this variable as protected and the only public variable left will be the int f(void);?

是的,C::var 现在是受保护的成员。

您可以通过尝试编译以下内容来测试它:

class B 
{
public:

    B() : var(0) { }

    int var;

protected:

private:

};


class C : public B 
{ 
public:

    C() : B() { }

protected: 

    using B::var;

private:

};

void main()
{
    B b;
    b.var = 3;    // <-- OK

    C c;
    c.var = 3;    // <-- error C2248
}

Also, could the class C inherit the variable as private by having private: using B::var; inside its body?

同样,是的,您可以将其继承为 private。虽然可以通过 B.

访问成员来规避
class B 
{
public:

    B() : var(0) { }

    int var;

protected:

private:

};


class C : public B
{ 
public:

    C() : B() { }

protected: 

private:

    using B::var;

};

class D : public C
{
public:

    D() : C() 
    { 
        B::var = 3;     // <-- OK
        C::var = 3;     // <-- error C2248
    };

protected:

private:

};

And is there any point of writing public: using B::var; since the variable var is already public inside class B?

不,没有意义。这是多余的。

有关详细信息,请参阅 Using-declaration: In class definition