简体   繁体   English

C++ 运算符过载错误

[英]C++ Operator Overload Error

I'm trying to create my own version of an array called a safearray, to test my knowledge of operator overloading and creating proper class's and such.我正在尝试创建我自己的称为 safearray 的数组版本,以测试我对运算符重载和创建适当类等的了解。

I'm encountering two errors.我遇到了两个错误。

SafeArray.h:11:15: error: 'const int SafeArray::operator' cannot be overloaded SafeArray.h:11:15: 错误:无法重载“const int SafeArray::operator”

SafeArray.h:10:10: error: with 'int& SafeArray::operator' SafeArray.h:10:10: 错误:使用“int& SafeArray::operator”

My code is split between three files.我的代码分为三个文件。

Main.cpp主.cpp

#include <cstdlib>
#include <iostream>

#include "SafeArray.h"

using namespace std;

int main(int argc, char** argv) {

    SafeArray a(10); // 10 integer elements

    for (int i = 0; i < a.length(); i++) {
        cout << i << " " << a[i] << "s" << endl; // values initialise to 0
    }

    cout << endl << a[1]; // Program exits here.

    a[3] = 42;
    cout << a[3];
    a[10] = 10;
    cout << a[10];
    a[-1] = -1; // out-of-bounds is "safe"?

    SafeArray b(20); // another array

    b = a; // array assignment

    for (int i = 0; i < b.length(); i++) {
        cout << b[i] << endl; // values copied from a
    }

    return 0;
}

SafeArray.h安全阵列.h

#ifndef SAFEARRAY_H
#define SAFEARRAY_H

class SafeArray {
public:
    SafeArray(int);              // int variable will be the array size
    int length();
    int boundsCheck(int y);       // constructor will call this function
//    const SafeArray operator= (const SafeArray&);
    int& operator[] (int y);
    const int operator [] (const int y); // you need this one too.

    SafeArray &operator=(SafeArray rhs) { 
    std::swap(array, rhs.array);
    std::swap(length_, rhs.length_);
        }

    SafeArray(SafeArray const &other);
    ~SafeArray();
private:
    int length_;
    int *array;
    //int array[];
};

#endif  /* SAFEARRAY_H */

SafeArray.cpp安全阵列.cpp

#include "SafeArray.h"
#include <iostream>

SafeArray::SafeArray(int x) {
    length_ = x;
    array = new int[length];
    for (int i = 0; i < length_; i++) {
        array[i] = 0;
    }
}

int SafeArray::length() {
    return this->length_;
}

int SafeArray::boundsCheck(int y) {

}

int& SafeArray::operator[] (int y) {
    return array[y];
}

SafeArray::~SafeArray() { 
    delete [] array;
}

SafeArray::SafeArray(SafeArray const &other) { 
    int *temp = new int[rhs.size_];
    for (int i=0; i<rhs.size_; i++)
        temp[i] = rhs.array[i];
    std::swap(temp, array);
    delete [] temp;
    return *this;
}

Your class definition isn't valid.您的 class 定义无效。 int array[] is an incomplete type, which must not appear as a (non-static) class member. int array[]是不完整的类型,不能作为(非静态)class 成员出现。 Some compilers accept this as a synonym for int array[0] , but zero-sized arrays are not valid in C++, either (only in C99).一些编译器接受它作为int array[0]的同义词,但零大小的 arrays 在 C++ 中也无效(仅在 C99 中)。

In short, you cannot write your code the way you do.简而言之,您不能按照您的方式编写代码。 You need to learn about dynamic allocation and manage your own memory. Check out how std::vector is implemented.需要学习动态分配,管理自己的memory。看看std::vector是如何实现的。

In C++11, I might recommend a std::unique_ptr<int[]> array as a quick-fix approach, to be initialized as array(new int[x]) .在 C++11 中,我可能会推荐一个std::unique_ptr<int[]> array作为快速修复方法,将其初始化为array(new int[x])

Actually int array[] is valid, and may appear as a class member.实际上 int array[] 是有效的,并且可能显示为 class 成员。 The following compiles with strict C++11 conformance:以下编译与严格的 C++11 一致性:

class foo 
{
public:
    foo() {}
    int length;
    int A[];
};

void ralph()
{
    foo *bar = (foo *)new int[ 21 ];
    bar->length = 20;
    bar->A[0] = 1;
}

This is legal, and has its advantages (occasionally).这是合法的,并且有其优势(偶尔)。 Although it is not commonly used.虽然不常用。

However, I suspect that the OP wanted something more along the lines of但是,我怀疑 OP 想要更多的东西

class SafeArray {
public:
    SafeArray(int);              // int variable will be the array size
    int length();
    int boundsCheck(int y);       // constructor will call this function

    int& operator[] (int y);
    const int operator [] (const int y) // you need this one too.
private:
    int length_;
    int *array;
};

along with随着

SafeArray::SafeArray(int x) {
    length_ = x;
    array = new int[length];
    for (int i = 0; i < length_; i++) {
        array[i] = 0;
    }
}

As @Kerrek already pointed out, your class definition is clearly wrong (shouldn't compile).正如@Kerrek 已经指出的那样,您的 class 定义显然是错误的(不应编译)。

To fix it, you want to change the definition to something like:要修复它,您需要将定义更改为:

int *array;

Then in your default ctor you could use something like this:然后在你的默认 ctor 中你可以使用这样的东西:

SafeArray::SafeArray(unsigned size = 0) 
    : array(new int[size])
{ 
    for (unsigned i=0; i<size; i++)
        array[i] = 0;
}

Then, yes, you'll need to write an assignment operator.然后,是的,您需要编写一个赋值运算符。 The usual way is called the copy and swap idiom.通常的方法称为复制和交换习语。 You create a copy, then swap the contents of the current one with those of the copy:您创建一个副本,然后将当前副本的内容与副本的内容交换:

SafeArray &operator=(SafeArray rhs) { 
    std::swap(array, rhs.array);
    std::swap(length_, rhs.length_);
}

Along with that, you'll need a copy constructor that makes a copy of the data as well:除此之外,您还需要一个复制构造函数来制作数据的副本:

SafeArray::SafeArray(SafeArray const &other) { 
    int *temp = new int[rhs.size_];
    for (int i=0; i<rhs.size_; i++)
        temp[i] = rhs.array[i];
    std::swap(temp, array);
    delete [] temp;
    return *this;
}

Finally, you'll need a destructor to destroy an object and (particularly) delete the memory it holds:最后,您需要一个析构函数来销毁 object 并(特别是)删除它持有的 memory:

SafeArray::~SafeArray() { 
    delete [] array;
}

Then realize that all of that is an ugly mess that will never really work well.然后意识到所有这些都是一团糟,永远不会真正有效。 In particular, the basic methodology is restricted to an array that's basically fixed in size.特别是,基本方法仅限于大小基本固定的数组。 As long as you only store int s, it's fairly easy to overlook the problems, and make a dynamic array that (sort of) works.只要您只存储int ,就很容易忽略这些问题,并制作一个(某种程度上)有效的动态数组。 When/if you want to store some other type, however, you just about need to separate allocating memory from initializing objects in that memory, which means throwing away essentially all the code above, and replacing it with something that:但是,当/如果您想要存储其他类型时,您只需要将分配 memory 与初始化该 memory 中的对象分开,这意味着基本上丢弃上面的所有代码,并将其替换为:

  1. keeps track of the array size and allocation size separately分别跟踪数组大小和分配大小
  2. allocates memory with ::operator new , an Allocator object, or something else similar使用::operator new分配 memory,分配器 object,或其他类似的东西
  3. uses placement new to initialize objects in the memory when needed.在需要时使用 placement new 来初始化 memory 中的对象。
  4. uses explicit destructor calls to destroy the objects使用显式析构函数调用来销毁对象
  5. uses ::operator delete to release memory使用::operator delete释放 memory

and so on.等等。 To summarize, std::vector is not a trivial piece of work.总而言之, std::vector不是一项微不足道的工作。

The error message refers to these two lines:错误消息指的是这两行:

int& operator[] (int y);
const int operator [] (const int y); // you need this one too.

Your error message says that (int y) and (const int y) are too similar to be two different overloads of the [] operator.您的错误消息说 (int y) 和 (const int y) 太相似了,不可能是 [] 运算符的两个不同重载。 You cannot overload on (int y) and (const int y) because the calls would all be ambiguous.您不能在 (int y) 和 (const int y) 上重载,因为这些调用都是模棱两可的。

You probably meant to return a const int if your SafeArray is const, but return an int& if your SafeArray is not const.如果您的 SafeArray 是常量,您可能打算返回一个 const int,但如果您的 SafeArray 不是常量,则返回一个 int&。 In that case, you declare the second function to apply to const SafeArray, by putting the word const after the parameter list.在这种情况下,您声明第二个 function 以应用于 const SafeArray,方法是将单词 const 放在参数列表之后。 This is what you should write in SafeArray.h:这是您应该在 SafeArray.h 中编写的内容:

int& operator[] (int y);
const int operator [] (int y) const; // you need this one too.

You would then have to write both of these functions in SafeArray.cpp:然后,您必须在 SafeArray.cpp 中编写这两个函数:

int& SafeArray::operator[] (int y) {
    return array[y];
}

const int SafeArray::operator[] (int y) const { // you need this one too.
    return array[y];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM