父类中的受保护数据在子类中不可用? [英] Protected data in parent class not available in child class?

查看:81
本文介绍了父类中的受保护数据在子类中不可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑:我认为受保护的数据是由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:


一个派生类可以访问一个基类的受保护成员,只为它自己的类型的对象....这防止了当一个派生类破坏属于其他派生类的数据时会发生的微妙错误。 / p>

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.

当然,这里有一个简单的方法来修复这种情况:

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;
}

这篇关于父类中的受保护数据在子类中不可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆