问题描述
可以有人请帮我错误
conversion from `A' to non-scalar type `B' requested
我有类A,派生自它B,但我对这些行有问题:
I have class A and derived from it B, but I have problems with these rows:
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();
};
编辑
(我不能改变它):
edited
I have this code and (I can't change it):
A a(1);
A *pb = new B(a);
B b = *pb;
我试图为B创建构造函数:
I tried to create constructor for 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;
}
但它给我一个错误,真的需要专业人士的帮助
but it gives me an error, really need help from professionals
推荐答案
您的问题是由于静态类型检查。当你有这条线:
Your problem is due to static type checking. When you have this line:
A *pb = new B(a);
pb
的静态类型为 A *
,它的动态类型是 B *
。虽然动态类型是正确的,编译器正在检查静态类型。
The static type of pb
is A *
and it's dynamic type is B *
. While the dynamic type is correct, the compiler is checking the static type.
对于这个简单的代码,因为你知道 pb
总是一个B,你可以使用静态转型修复这个问题:
For this simple code, since you know the dynamic type of pb
is always a B, you can fix this with a static cast:
B b = *static_cast<B *>(pb);
但是请注意,如果动态类型 pb
是 A *
,会导致未定义的行为。
But be warned that if the dynamic type of pb
was an A *
the cast would cause undefined behavior.
这篇关于非标量类型请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!