gpt4 book ai didi

c++ - 这段禁止继承的代码是如何工作的?

转载 作者:太空狗 更新时间:2023-10-29 23:08:59 25 4
gpt4 key购买 nike

我发现了一些相当奇怪的代码:

class Base {
public:
virtual bool IsDerived() const { return false; }
};

class Derived : public Base {
public:
bool IsDerived() const { return true; }
};

Derived* CastToDerived( Base* base )
{
// private and protected inheritance from Derived is prohibited
Derived* derived = dynamic_cast<Derived*>(base);
if( derived == 0 ) {
assert( !base->IsDerived() );
}
return derived;
}

我不明白有关私有(private)和 protected 继承的段落。

假设,我从 Derived 继承了 protected 修饰符:

class FurtherDerived : protected Derived {
};

会发生什么? 断言将如何被触发?

最佳答案

如果你有一个 ProtectedPrivate继承,你不能这样做:

Base *ptr = new Derived();

你也做不到,

Derived *ptr1 = new Derived();
Base *ptr = ptr1;

这是因为,BaseDerived 的不可访问基础

因为你不能有 Base指向 Derived 的类指针类对象,该检查看起来多余。


编辑:
即使您不能直接分配 Derived类对象到 Base类指针,它可能以其他方式发生,例如:如果 Derived 的函数类返回 Base类指针。

简而言之,A Base类指针可能指向 Derived类对象,即使派生是 protectedprivate .

鉴于上述情况,

按照 C++ 标准:
5.2.7.8:

The run-time check logically executes as follows:
— If, in the most derived object pointed (referred) to by v, v points (refers) to a public base class sub- object of a T object, and if only one object of type T is derived from the sub-object pointed (referred) to by v, the result is a pointer (an lvalue referring) to that T object.
Otherwise, if v points (refers) to a public base class sub-object of the most derived object, and the type of the most derived object has a base class, of type T, that is unambiguous and public, the result is a pointer (an lvalue referring) to the T sub-object of the most derived object.
— Otherwise, the run-time check fails.

请注意,该标准明确要求派生是公开的。
因此 dynamic_cast如果推导是 protected,将检测到将转换视为不正确的转换或 private并返回 NULL (因为您使用的是指针)和 assert将被调用。

所以是的,代码非常有效。它确实按照评论所说的做了


这个 sample ,证明它按照评论工作:

#include<iostream>
class Base
{
public:
virtual bool IsDerived() const { return false; }
};

class Derived : protected Base
{
public:
bool IsDerived() const { return true; }
Base* getBase() { return this; }
};

Derived* CastToDerived( Base* base )
{
// private and protected inheritance from Derived is prohibited
Derived* derived = dynamic_cast<Derived*>(base);
if( derived == 0 )
{
std::cout<< "!base->IsDerived()";
}
return derived;
}


int main()
{
Derived *ptr3 = new Derived();
Base *ptr = ptr3->getBase();
Derived *ptr2 = CastToDerived(ptr);
return 0;
}

关于c++ - 这段禁止继承的代码是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7207384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com