gpt4 book ai didi

c++ - 父类中 protected 数据在子类中不可用?

转载 作者:可可西里 更新时间:2023-11-01 15:11:14 26 4
gpt4 key购买 nike

我很困惑:我认为 protected 数据可由 C++ 中给定类的子级读取/写入。

以下代码片段无法在 MS 编译器中编译

class A
{
protected:
int data;
};

class B : public A
{
public:

B(A &a)
{
data = a.data;
}
};

int main()
{
A a;
B b = a;
return 0;
}

错误信息:

Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86
Copyright (C) Microsoft Corporation. All rights reserved.

demoFail.cpp
demoFail.cpp(12) : error C2248: 'A::data' : cannot access protected member declared in class 'A'
demoFail.cpp(4) : see declaration of 'A::data'
demoFail.cpp(2) : see declaration of 'A'

我做错了什么?

最佳答案

根据 TC++PL,第 404 页:

A derived class can access a base class’ protected members only for objects of its own type.... This prevents subtle errors that would otherwise occur when one derived class corrupts data belonging to other derived classes.

当然,这里有一个简单的方法可以解决您的问题:

class A
{
protected:
int data;
};

class B : public A
{
public:
B(const A &a)
: A(a)
{
}
};

int main()
{
A a;
B b = a;
return 0;
}

关于c++ - 父类中 protected 数据在子类中不可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1414506/

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