C++ 自动"类型转换"转换

c++ automatic 'type cast' conversion

本文关键字:转换 类型转换 C++ 自动      更新时间:2023-10-16

有人可以解释为什么下面的代码在错误时无法编译:

Error   1   error C2243: 'type cast' : conversion from 'Der *' to 'Base *' exists, but is inaccessible  d:userslzizvadocumentsmtac++projectstemp117022014.cpp   50  1   temp1
Error   2   error C2243: 'type cast' : conversion from 'Der *' to 'Base *' exists, but is inaccessible  d:userslzizvadocumentsmtac++projectstemp117022014.cpp   51  1   temp1
    3   IntelliSense: conversion to inaccessible base class "Base" is not allowed   d:userslzizvadocumentsmtac++projectstemp117022014.cpp   50  12  temp1
    4   IntelliSense: conversion to inaccessible base class "Base" is not allowed   d:userslzizvadocumentsmtac++projectstemp117022014.cpp   51  14  temp1

我认为当存在私有继承时,子项会获取所有属性和方法,并将它们设置为私有,并且只应影响子项的子类。我在这里错过了什么?编译器实际上做了什么?

提前感谢,利龙

#include <iostream>
using namespace std;
class Base
{
int n;
Base* next;
public:
Base(int n, Base* next = NULL) : n(n), next(next)
{}
virtual void print() const
{
cout << n << endl;
if (next != NULL)
{
next->print();
}
}
virtual ~Base()
{
cout << "Base" << endl;
}
};
class Der : private Base
{
int counter;
public:
Der(int n, Base* next = NULL) : Base(n, next), counter(n){}
void print() const
{
cout << counter << endl;
Base::print();
}
~Der()
{
cout << "Der" << endl;
}
};
void main()
{
Der one(1);
Der two(2, &one);
Der three(3, &two);
three.print();
}

问题出在twothree的构造上:Der构造函数采用Base*,但你传递的是Der*指针。

因为Der私下从Base派生,Der-> Base转换在main()中是不可访问的,因此错误。

尽管基类型和派生类型之间存在紧密耦合,但私有继承是一种"has-a"关系,而不是"is-a"。它确实适合继承实现,而不是接口,并且,正如您所发现的,它不能用于多态性,因为指向基类型的引用或指针无法绑定到派生类型的实例。

当您拨打此电话时

Der two(2, &one);

您正在尝试将&oneDerived*绑定到Base*

有关私人继承的更多信息,请参阅继承的用途和滥用GOTW。