VC12和VC14对c++友好和继承的不同行为
Different behavior about c++ Friendship and inheritance from VC12 and VC14
class Base
{
protected:
void func1();
};
class Derived : public Base
{
friend class Third;
};
class Third
{
void foo()
{
Derive d;
d.func1();
}
};
我可以在VC14 (Visual Studio 2015)中编译代码而没有错误但是从VC12 (Visual Studio 2013)得到错误
cannot access protected member declared in class 'Base'
谁是对的?这种与继承的友谊的正确性是什么?
from MSDN https://msdn.microsoft.com/en-us/library/465sdshe.aspx or http://en.cppreference.com/w/cpp/language/friend看起来友谊是不可传递的,不能被继承。然而,我认为这不是这个代码示例的实际情况。
但是为什么VC14不会给我一个错误?
如果VC14是正确的,我如何"修改"代码,使VC12也可以吗?定义受保护的func1()再次在类派生?
修复错别字后,注释内联:
class Base
{
protected:
void func1(); // protected access
};
class Derived : public Base
{
// implicit protected func1, derived from Base
// this means 'make all my protected and private names available to Third'
friend class Third;
};
class Third
{
void foo()
{
Derived d;
// func1 is a protected name of Derived, but we are Derived's friend
// we can therefore access every member of Derived
d.func1();
}
};
VC14是正确的
VC12的可能解决方案:
class Base
{
protected:
void func1();
};
class Derived : public Base
{
protected:
using Base::func1;
private:
friend class Third;
};
class Third
{
void foo()
{
Derived d;
d.func1();
}
};
另一个可能的解决方案(使用基于键的访问)
class Third;
class Func1Key
{
private:
Func1Key() = default;
friend Third;
};
class Base
{
protected:
void func1();
};
class Derived : public Base
{
public:
void func1(Func1Key)
{
Base::func1();
}
};
class Third
{
void foo()
{
Derived d;
d.func1(Func1Key());
}
};
相关文章:
- 继承函数的重载解析
- 继承期间显示未知行为的子类
- 头文件-继承c++
- 为什么在保护模式下继承升级不起作用
- 通过继承类使用来自不同命名空间的运算符
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 混合组合和继承的C++问题
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 从类继承时,继承的类是否会通过父类重新定义继承的变量
- 公共与私人继承
- 如何创建从同一类继承的不同对象的向量
- 如何从另一个文件继承私有成员变量和公共函数
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 带有继承的C++工厂
- 我应该避免多重实现继承吗
- C++继承更改成员
- 从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明
- 关于C++中具有多重继承"this"指针的说明
- 尝试使用继承和模板实现CRTP.Visual Studio正在生成编译器错误
- VC12和VC14对c++友好和继承的不同行为