为什么我不能在此代码中将 A* 转换为 B*?
Why can't I convert an A* to a B* in this code?
我不明白我在做什么错。我收到错误:上面的行:
从a*到b*的无效转换: B *p3=new A(p2->operator+(*p1));
这是完整的代码。
#include <iostream>
using namespace std;
#include <iostream>
using namespace std;
class A
{
protected: int x;
public: A(int i=-31) {x=i;}
virtual A operator+(A a) {return x+a.x;}
};
class B:public A
{
public:B(int i=12) {x=i;}
B operator+(B b) {return x+b.x+1;}
void afisare() {cout<<x;}
};
int main()
{
A *p1=new B, *p2=new A;
B *p3=new A(p2->operator+(*p1));
p3->afisare();
//cout << "Hello world!" << endl;
return 0;
}
我认为您在这里有继承。如果您具有A*
类型的指针,则可以指向类型A
的对象或类型B
的对象,因为B
类型的对象也是类型A
的对象。但是,您不能在类型A
的对象上具有类型B*
点的指针,因为并非所有类型A
的对象都属于B
类型。
独立,您可以重写该行
B *p3 = new A(p2->operator+(*p1));
AS
B* p3 = new A(p2 + *p1);
这可能会使内容更容易阅读。
多态性仅以一种方式起作用。基本指针可以指向派生的类,因为派生类的所有内容都具有基类所做的一切。但是,派生的指针不能指向基础,因为派生的类有基类没有的东西。
class A
{
}
class B:public A
{
}
upcasting:A *a=new B;
(主要是在覆盖时使用)
降低:B *b=(B*)a;
仅在您要施放的指针(在我们的情况下a
)指向混凝土派生对象时才有效。
相关文章:
- 不能将复制初始化与隐式转换的多个步骤一起使用
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 为什么此指针值不能转换为整数的规则是什么?
- 为什么我可以隐式地将字符*转换为常量字符*,但不能将无符号字符*
- 不能在 if 语句 - c++ 中使用 void func 直接将字符串转换为大写
- 用户定义的转换不能在C++中使用static_cast
- 不能将字符转换为整数吗?
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 为什么我们不能将使用异或运算找到的整数转换为字符?
- 我把我的编译器从32位转换为64位,但我仍然不能使用超过2GB:(为什么
- 为什么我们不能使用整数到字符串直接转换,但可以按位到字符串?
- 为什么不能指向指针,在没有强制转换的情况下访问结构成员?
- 不能(隐式地)从字符**转换为常量字符**吗?
- 类型"const char[2]"的值不能隐式转换为"int"错误C++
- 为什么用户定义的转换函数模板不能有推导的返回类型?
- 不能将结构push_back() 转换为 std::vector<std::shared_ptr<theStruct>> theVector
- 不能返回派生的类(无法转换)
- 已弃用从字符串常量到“char*”的转换:不能使用该常量
- C样式强制转换可以处理的转换,但C++强制转换不能
- 从char*到wchar*的转换不能正常工作