本文介绍了父类中的受保护数据在子类中不可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很困惑:我认为受保护的数据是由C ++中给定类的子类读/写的。
I am confused: I thought protected data was read/writable by the children of a given class in C++.
下面的代码片段无法在MS Compiler
The below snippet fails to compile in MS Compiler
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,pg 404:
According to TC++PL, pg 404:
当然,这里有一个简单的方法来修复这种情况:
Of course, here's an easy way to fix this for your case:
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;
}
这篇关于父类中的受保护数据在子类中不可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!