C++ 自动"类型转换"转换
c++ automatic 'type cast' conversion
有人可以解释为什么下面的代码在错误时无法编译:
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();
}
问题出在two
和three
的构造上:Der
构造函数采用Base*
,但你传递的是Der*
指针。
因为Der
私下从Base
派生,Der
-> Base
转换在main()
中是不可访问的,因此错误。
尽管基类型和派生类型之间存在紧密耦合,但私有继承是一种"has-a"关系,而不是"is-a"。它确实适合继承实现,而不是接口,并且,正如您所发现的,它不能用于多态性,因为指向基类型的引用或指针无法绑定到派生类型的实例。
当您拨打此电话时
Der two(2, &one);
您正在尝试将&one
、Derived*
绑定到Base*
。
有关私人继承的更多信息,请参阅继承的用途和滥用GOTW。
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++中的双指针类型转换
- 逐位操作的隐式类型转换
- 模板中的类型转换
- 在 C++(和 C)中进行类型转换时明显不一致
- 字符类型转换不兼容
- 将复杂的非基元C++数据类型转换为 Erlang/Elixir 格式,以使用 NIF 导出方法
- C++:用户定义的显式类型转换函数错误
- 无法转换类型 C++
- 将类指针类型转换为键时出错
- 通过引用传递参数时C++类型转换
- 在 C++ 中将一个模板类型的对象类型转换为另一个模板类型
- C++显式类型转换(C 样式强制转换)的强制表示法和static_cast的多种解释
- C++无效的函数类型转换
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 如何将Windows产品类型转换为名称?
- 通过构造函数方法输出的类到类类型转换是 5500 为什么不是 5555
- 事件系统:使用类型转换或联合进行继承
- 想要将字符数组的部分转换/类型转换为值