gpt4 book ai didi

c++ - 请求非标量类型

转载 作者:行者123 更新时间:2023-11-30 00:41:42 24 4
gpt4 key购买 nike

谁能帮我解决一个错误

conversion from `A' to non-scalar type `B' requested

我有类 A 并派生自它 B,但我对这些行有问题:

A a(1);
A *pb = new B(a);
B b = *pb; //here I have an error

在此先感谢您的帮助

class A {
protected:
int player;
public:
A(int initPlayer = 0);
A(const A&);
A& operator=(const A&);
virtual ~A(){};
virtual void foo();
void foo() const;
operator int();
};

class B: public A {
public:
B(int initPlayer): A(initPlayer){};
~B(){};
virtual void foo();
};

已编辑

我有此代码并且(我无法更改它):

A a(1);
A *pb = new B(a);
B b = *pb;

我试图为 B 创建构造函数:

B::B(const A & a):
player(a.player){}

B& B::operator=(const A& a){
if(this == &a){
return *this;
}
player = a.player;
return *this;
}

但它给了我一个错误,真的需要专业人士的帮助

最佳答案

您的问题是由于静态类型检查引起的。当你有这条线时:

A *pb = new B(a);

pb的静态类型是A *,动态类型是B *。虽然动态类型是正确的,但编译器正在检查静态类型。

对于这个简单的代码,由于您知道 pb 的动态类型始终是 B,因此您可以使用静态转换来解决此问题:

B b = *static_cast<B *>(pb); 

但请注意,如果 pb 的动态类型是 A *,则转换会导致未定义的行为。

关于c++ - 请求非标量类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3046463/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com