gpt4 book ai didi

c++ - 友情与传承

转载 作者:行者123 更新时间:2023-11-28 03:11:56 24 4
gpt4 key购买 nike

假设我有这段代码:

#include <iostream>
using namespace std;

class A
{
protected:
virtual ~A() { cout << "A destructor reached." << endl;}

friend class Z;
};

class B : public A
{
protected:
virtual ~B() { cout << "B destructor reached." << endl; }
};

class Z
{
public:
void Test();

friend class A;
};

void Z::Test()
{
A* derived = (A*) new B();

delete derived;
}

int main()
{
Z test;
test.Test();
}

会发生什么,B的析构函数会被调用吗?合法吗?如果不是,是否有任何方法可以调用派生的构造函数而不使每个类都派生自 A friend of Z?

最佳答案

标准,§11.5/1“访问虚函数”说

The access rules (Clause 11) for a virtual function are determined by its declaration and are not affected by the rules for a function that later overrides it.

因此只要您有权访问A::~A,就可以调用B::~B。但是您必须通过 A 调用它,因为 Z 无法访问 B

顺便说一句,Z 中的友元声明是无用的,因为其中没有任何内容是私有(private)的或 protected 。

关于c++ - 友情与传承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18185930/

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