天道酬勤,学无止境

non-scalar type requested

can somebody please help me with an error

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

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

thanks in advance for any help

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;    

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);

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.

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); 

But be warned that if the dynamic type of pb was an A * the cast would cause undefined behavior.

When you dereference an 'A' pointer, you get an 'A' even if it points to a 'B'. Polymorphism does not come into play here! To preserve the 'B' properties to the 'A' object you should properly cast the initialization as explained in some of the other answers.

In such situations a dynamic cast is most appropriate. Dynamic cast will invoke the runtime type system to figure out the "real" type of bp and will return 0 if it can't be cast to the requested type. As you know the real type you could also use static_cast here but generally this isn't the case in such situations.

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

*pb will give you a A& and not a B&. It's just like pb being an A* and not a B* even though the actual object is a B.

B b = *pb will attempt to copy-construct a B using a synthesised copy constructor. The copy constructor will therefore be looking for a B& as its argument. You have no constructor to make a B from an A, hence the error.

As @R Samuel Klatchko says you could just cast it or, in the case you've given, you could just make pb actually be a B*.

You are trying to assign an object of type A to object of type B. Which is not allowed unless you define a type cast operator. pb is a pointer to A object and in general it is not a pointer to B (in your case it is, but it doesn't matter for the compiler, since it's declared as pointer to A). To make such assignement possible, you first need to down-cast pb to pointer of B (as R Samuel Klatchko pointed out, in your case static_cast is perfectly fine; in other cases you might need use dynamic_cast).

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • Error: Conversion to non-scalar type requested
    I'm having a small problem trying to malloc this struct. Here is the code for the structure: typedef struct stats { int strength; int wisdom; int agility; } stats; typedef struct inventory { int n_items; char **wepons; char **armor; char **potions; char **special; } inventory; typedef struct rooms { int n_monsters; int visited; struct rooms *nentry; struct rooms *sentry; struct rooms *wentry; struct rooms *eentry; struct monster *monsters; } rooms; typedef struct monster { int difficulty; char *name; char *type; int hp; } monster; typedef struct dungeon { char *name; int n_rooms; rooms *rm; }
  • Conversion from 'myItem*' to non-scalar type 'myItem' requested
    I have this C++ code: #include <iostream> using namespace std; struct MyItem { int value; MyItem* nextItem; }; int main() { MyItem item = new MyItem; return 0; } And I get the error: error: conversion from `MyItem*' to non-scalar type `MyItem' requested Compiling with g++. What does that mean? And what's going on here?
  • Error: Conversion to non-scalar type
    I am making a set of derived classes for an assignment. I am instructed to use char arrays (c-strings). When I compile I keep getting the error: Homework11.cpp: In function âint main()â: Homework11.cpp:72: error: conversion from âchar [10]â to non-scalar type âBusinessâ requested Homework11.cpp:73: error: conversion from âchar [10]â to non-scalar type âBusinessâ requested Homework11.cpp:74: error: conversion from âchar [10]â to non-scalar type âAccountâ requested Homework11.cpp:75: error: conversion from âchar [10]â to non-scalar type âAccountâ requested I am fairly certain that my problem is
  • 请求从“myItem*”转换为非标量类型“myItem”(Conversion from 'myItem*' to non-scalar type 'myItem' requested)
    问题 我有这个 C++ 代码: #include <iostream> using namespace std; struct MyItem { int value; MyItem* nextItem; }; int main() { MyItem item = new MyItem; return 0; } 我得到错误: error: conversion from `MyItem*' to non-scalar type `MyItem' requested 用 g++ 编译。 这意味着什么? 这是怎么回事? 回答1 尝试: MyItem * item = new MyItem; 但不要忘记在使用后删除它: delete item; 回答2 你混了 MyItem item; 它在堆栈上分配了一个MyItem实例。 实例的内存在封闭范围结束时自动释放 和 MyItem * item = new MyItem; 它在堆上分配一个MyItem实例。 您将使用指针引用此实例,并且在使用完delete item后需要显式释放内存。 回答3 首先,这段代码将无法编译,因为您忘记了每个成员变量声明之后和MyItem声明之后的分号,并且键入了错误的关键字“struct”。 您的代码应如下所示: struct MyItem { var value; MyItem* nextItem; }
  • conversion from 'KanjiCard*' to non-scalar type 'KanjiCard' requested (custom enum)
    Okay, I've tried using Google-sensei and searching around on this website, and while I've found many posts about this error, I haven't found any that have addressed enums. Also, all the ones I have seen have either been someone trying to assign one type to another, improper use of 'new', etc. As far as I can tell, that's not the case in this instance. As stated in the title, I'm getting an error conversion from 'KanjiCard*' to non-scalar type 'KanjiCard' requested when trying to compile the program I'm working on using g++. I have a class named KanjiCard that has this publicly-defined enum
  • 错误:转换为非标量类型(Error: Conversion to non-scalar type)
    问题 我正在为作业制作一组派生类。 我被指示使用字符数组(c 字符串)。 当我编译时,我不断收到错误: Homework11.cpp: In function âint main()â: Homework11.cpp:72: error: conversion from âchar [10]â to non-scalar type âBusinessâ requested Homework11.cpp:73: error: conversion from âchar [10]â to non-scalar type âBusinessâ requested Homework11.cpp:74: error: conversion from âchar [10]â to non-scalar type âAccountâ requested Homework11.cpp:75: error: conversion from âchar [10]â to non-scalar type âAccountâ requested 我相当确定我的问题出在我尝试将实例变量 Name 设置为传入的参数的地方。这是我的代码,其中包含我认为可能存在问题的注释。 #include <iomanip> #include <iostream> #include <cstdlib> #include
  • C++ Error: Conversion to Non-Scalar Type [closed]
    This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 8 years ago. I seem to be having a peculiar error in the following code segment (ignore the excess header files and the blank main function, I just wanted to isolate this problem into a compileable .cpp file for posting here). It says error conversion from '[some type I
  • C++ 错误:转换为非标量类型 [关闭](C++ Error: Conversion to Non-Scalar Type [closed])
    问题 这个问题不太可能对任何未来的访客有帮助; 它只与一个小的地理区域、一个特定的时间点或一个非常狭窄的情况相关,通常不适用于互联网的全球受众。 如需帮助使此问题更广泛地适用,请访问帮助中心。 8 年前关闭。 我在下面的代码段中似​​乎有一个特殊的错误(忽略多余的头文件和空白的 main 函数,我只是想把这个问题隔离到一个可编译的 .cpp 文件中以便在这里发布)。 它表示从“[我定义的某种类型]”到非标量类型“[我定义的某种类型]”的错误转换。 这个特定示例中的代码应该将一组字符串列表作为一个输入参数(命名输入),并将对字符串列表的引用作为另一个(命名输出),并从中计算出最长的字符串公共前缀列表输入中的列表并将结果存储到输出中。 编译器错误消息(也作为注释包含在相应行中是这样的: lcp.cpp:28:47: 错误:从“ std::list<std::basic_string<char> >::const_iterator {aka std::_List_const_iterator<std::basic_string<char> >} ”到非标量的转换请求类型' std::list<std::basic_string<char> >::iterator {aka std::_List_iterator<std::basic_string<char> >} ' 这是实际的程序:
  • error: conversion from 'const char [5]' to non-scalar type in c++
    public: string str; Test(string& str){ this->str=str; cout<<"constructor"<<endl; } }; int main() { Test t="test"; return 0; } why popup "..\src\Test.cpp:30:9: error: conversion from 'const char [5]' to non-scalar type 'Test' requested "? but why it is ok in followed code? #include <iostream> using namespace std; class Test{ public: string str; Test(string str){ this->str=str; cout<<"constructor"<<endl; } Test(const Test &test){ cout<<"copy constructor"<<endl; this->str=test.str; } }; int main() { Test t=Test("test"); return 0; }
  • How can I fix this error `conversion from const_iterator to non-scalar type`?
    can someone explain what is the mention of this error: conversion from 'std::vector<int, std::allocator<int> >::const_iterator {aka __gnu_cxx::__normal_iterator<const int*, std::vector<int, std::allocator<int> > >}' to non-scalar type 'std::vector<int, std::allocator<int> >::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >}' requested given the following class: #include <vector> #include <iostream> using std::vector; using std::ostream; template<class T> class Gen { vector<T> array; public: explicit Gen(int size); template<class S> friend ostream&
  • 错误:在 C++ 中从“const char [5]”转换为非标量类型(error: conversion from 'const char [5]' to non-scalar type in c++)
    问题 public: string str; Test(string& str){ this->str=str; cout<<"constructor"<<endl; } }; int main() { Test t="test"; return 0; } 为什么弹出“..\src\Test.cpp:30:9: 错误:从 'const char [5]' 转换为非标量类型 'Test' 请求”? 但为什么在后面的代码中没问题? #include <iostream> using namespace std; class Test{ public: string str; Test(string str){ this->str=str; cout<<"constructor"<<endl; } Test(const Test &test){ cout<<"copy constructor"<<endl; this->str=test.str; } }; int main() { Test t=Test("test"); return 0; } 回答1 Test t="test"; 这试图: 将字符串文字(它是一个字符数组, char[5] )转换为临时string 将临时string转换为Test 这失败有两个原因: 隐式转换序列不能涉及多个用户定义的转换。 这里需要两个。
  • Read variables from global environment with inline Rcpp?
    I'm following the example from the Rcpp intro Vignette, trying it with inline. f<-cxxfunction(signature(), plugin="Rcpp", body=" Environment global = Environment::global_env(); std::vector<double> vx = global['x']; ") but I get a compile error. file12384509.cpp: In function 'SEXPREC* file12384509()': file12384509.cpp:31: error: invalid use of incomplete type 'struct SEXPREC' C:/PROGRA~1/R/R-211~1.1/include/Rinternals.h:333: error: forward declaration of 'struct SEXPREC' file12384509.cpp:31: error: conversion from 'SEXPREC' to non-scalar type 'std::vector<double, std::allocator<double> >'
  • Why does std::optional::operator=(U&&) require U to be a non-scalar type?
    For optional's template<class U = T> optional<T>& operator=(U&& v); the standard demands that (see [optional.assign]/3.16): This function shall not participate in overload resolution unless ... conjunction_v<is_scalar<T>, is_same<T, decay_t<U>>> is false ... Why do we have to exclude case when assigning a scalar of type U == T?
  • Why can't I push this object onto my std::list?
    Just started programming in C++. I've created a Point class, a std::list and an iterator like so: class Point { public: int x, y; Point(int x1, int y1) { x = x1; y = y1; } }; std::list <Point> pointList; std::list <Point>::iterator iter; I then push new points onto pointList. Now, I'm needing to iterate through all the points in pointList, so I need to loop using the iterator. This is where I get screwed up. for(iter = pointList.begin(); iter != pointList.end(); iter++) { Point currentPoint = *iter; glVertex2i(currentPoint.x, currentPoint.y); } Update You guys were right, the problem isn't in
  • 创建一个可以用赋值初始化但不可复制的类型(creating a type which can be initialized with assignment, but is not copyable)
    问题 我正在寻找一种类型,该类型可以通过其他类型的赋值进行初始化,但不能被复制。 这个想法类似于范围智能指针的想法,因为我希望这种类型的对象在其生命周期内拥有一个资源,但我也希望能够使用赋值语法。 所以在概要中,这就是我想要的: T x = new U; // allowed T y(new U); // allowed T z = x; // not allowed T x2(x) // not allowed 这是我迄今为止尝试过的... #include <boost/noncopyable.hpp> class U {}; class T : boost::noncopyable { public: T(U *p) : p_(p) { } ~T() { delete p_; } operator bool() const { return p_ != 0; } private: U *p_; }; int main() { T x = new U; // allowed T y(new U); // allowed //T z = x; // not allowed //T x2(x) // not allowed } 不幸的是,这会导致错误: $ g++ test.cc -o test /usr/include/boost/noncopyable.hpp
  • Scipy filter with multi-dimensional (or non-scalar) output
    Is there a filter similar to ndimage's generic_filter that supports vector output? I did not manage to make scipy.ndimage.filters.generic_filter return more than a scalar. Uncomment the line in the code below to get the error: TypeError: only length-1 arrays can be converted to Python scalars. I'm looking for a generic filter that process 2D or 3D arrays and returns a vector at each point. Thus the output would have one added dimension. For the example below I'd expect something like this: m.shape # (10,10) res.shape # (10,10,2) Example Code import numpy as np from scipy import ndimage a = np
  • Assign value to the same field of every element of non-scalar struct
    In Matlab, assigning cell arrays to a struct arrays field foo is possible with my_array(1000).foo = []; [my_array.foo] = some_cell{:}; Now what I would like to do is assign a single value to all fields in the array. But whatever I tried, Matlab would return error messages instead of silently assuming that if I want to assign a single element of size [1x1], it should be assigned to all fields. I would be happy if I could simply say e.g.: my_array.foo = pi; ??? Incorrect number of right hand side elements in dot name assignment. Missing [] around left hand side is a likely cause. So, how can I
  • 为非标量结构的每个元素的相同字段赋值(Assign value to the same field of every element of non-scalar struct)
    问题 在 Matlab 中,可以将元胞数组分配给结构数组字段foo my_array(1000).foo = []; [my_array.foo] = some_cell{:}; 现在我想做的是为数组中的所有字段分配一个值。 但是无论我尝试什么,Matlab 都会返回错误消息,而不是默默地假设如果我想分配一个大小为[1x1]元素,它应该分配给所有字段。 如果我可以简单地说,例如: my_array.foo = pi; ??? Incorrect number of right hand side elements in dot name assignment. Missing [] around left hand side is a likely cause. 那么,如何将单个值分配给整个结构数组中的字段? 回答1 您可以使用deal来解决这个问题: my_array(1000).foo = []; [my_array.foo] =deal(pi); 但是,请注意第二行中的方括号是将逗号分隔的列表my_array.foo临时转换为向量所必需的。
  • 如何在类模板中使用函子作为成员?(How to use functor as a member in class template?)
    问题 我试图在类模板中使用函子作为std::function对象。 以下是我到目前为止所做的。 //! the functor class template template<typename T> struct func { void operator ()(T t) { std::cout << t << "\n"; } }; //! the class template that holds a std::function object as a member template<typename T> struct Foo { std::function<void(T)> bar = func<T>(); }; int main() { Foo<int> foo; return 0; } 有人抱怨说 error: conversion from 'func<int>' to non-scalar type 'std::function<void(int)>' requested struct Foo ^ 有可能这样做吗? 如何解决? 回答1 您可以将其设为静态并在类范围之外对其进行初始化,也可以在构造函数中对其进行初始化。 在 GCC 4.7.2 上测试。 template<typename T> struct Foo { static std::function<void
  • 具有多维(或非标量)输出的 Scipy 过滤器(Scipy filter with multi-dimensional (or non-scalar) output)
    问题 是否有类似于ndimage的 generic_filter 支持向量输出的过滤器? 我没有设法让scipy.ndimage.filters.generic_filter返回的不仅仅是一个标量。 取消注释以下代码中的行以获取错误: TypeError: only length-1 arrays can be converted to Python scalars 。 我正在寻找一个处理 2D 或 3D 数组并在每个点返回一个向量的通用过滤器。 因此,输出将增加一个维度。 对于下面的示例,我希望是这样的: m.shape # (10,10) res.shape # (10,10,2) 示例代码 import numpy as np from scipy import ndimage a = np.ones((10, 10)) * np.arange(10) footprint = np.array([[1,1,1], [1,0,1], [1,1,1]]) def myfunc(x): r = sum(x) #r = np.array([1,1]) # uncomment this return r res = ndimage.generic_filter(a, myfunc, footprint=footprint) 回答1 generic