c++ - 错误 C2535 : 'ManagedArray::ManagedArray(void)'

标签 c++

我正在做一个项目,在多次搜索标题中的错误后,我几乎迷路了。如果可以的话,请获得一些帮助来解决这个问题。

class ManagedArray
{

    public:

     float *elements;
     int numberOfElements; 

     /* default constructor */
     ManagedArray() :elements(NULL){};
     ManagedArray() :numberOfElements(0){}; <--Where the error is

     /*accessor*/
     int size() {return numberOfElements; }
     float get(int index) {return elements[index]; }

最佳答案

根据 C++ 标准(9.2 类成员)

  1. ...A member shall not be declared twice in the member-specification, except that a nested class or member class template can be declared and then later defined, and except that an enumeration can be introduced with an opaque-enum-declaration and later redeclared with an enum-specifier.

你声明并定义了两次默认构造函数

 ManagedArray() :elements(NULL){};
 ManagedArray() :numberOfElements(0){}; <--Where the error is

例如,您可以向第二个构造函数添加一个参数

 ManagedArray() :elements(NULL){};
 ManagedArray( int n ) :numberOfElements(n){};

或以下方式

 explicit ManagedArray( int n ) :numberOfElements(n){};
 ^^^^^^^^

考虑到数据成员 numberOfElements 最好使用 size_t 类型而不是类型 int 至少因为元素的数量不能为负。

此外,两个构造函数都应初始化所有数据成员。

例如

 ManagedArray() :elements(NULL), numberOfElements( 0 ){};

关于c++ - 错误 C2535 : 'ManagedArray::ManagedArray(void)' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34979554/

相关文章:

c++ - 使用模板参数传递链表的节点类型和数据类型

c++ - 防止在基类和派生类上使用 delete,同时允许使用 new

c++ - 为什么我的类(class)规模大于其成员的总和?

c++ - 函数模板编译器错误

c++ - 作业 : Array's for C++

c++ - 当局部变量具有相同名称时,如何在 C++ 中分配给实例变量?

c++ - 对象的静态成员 vector 的const_cast

c++ - ZeroMQ 3.2.5 在 mailbox_t::recv 中的访问冲突

c++ - 重载函数调用在 C++ 中如何工作?

c++ - Ostream& operator<< 重载代码不起作用