Перегрузка оператора [] - программирование
Подтвердить что ты не робот

Перегрузка оператора []

Я новичок в C++. Я изучаю, как перегружать операторов. Я создал класс Complex, представляющий комплексные числа и методы для сложной арифметики и класс ComplexArray, который представляет массивы фиксированной длины элементов в комплексном векторном пространстве C.

Я получаю ошибки компилятора, что он не может найти правильную форму оператора []. Однако я искал в Интернете, и я не могу исправить ошибку. Любые подсказки/подсказки в правильном направлении окажут огромную помощь.

Код серьезности Описание Состояние подавления строки файла проекта
Ошибка C2676 binary '[': 'const ComplexArray' не определяет этот оператор или преобразование в тип, приемлемый для предопределенного оператора ComplexArrays c:\users\quasa\source\repos\complexarrays\complexarrays\testcomplexarray.cpp 7

Вот мой код:

TestComplexArray.cpp

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

Complex ComplexSum(const ComplexArray& cArray, int size)
{
    Complex sum = cArray[0];
    for (int i = 1; i < size; i++)
    {
        sum = sum + cArray[i];
    }
    return sum;
}

Complex ComplexProduct(const ComplexArray& cArray, int size)
{
    Complex product = cArray[0];
    for (int j = 1; j < size; j++)
    {
        product = product * cArray[j];
    }
    return product;
}

int main()
{
    char ch;

    const int size = 5;
    ComplexArray cArray(size);

    for (int i = 0; i < size; i++)
    {
        cArray[i] = Complex((double)(i + 1), 0);
        std::cout << cArray[i];
    }

    Complex sum = ComplexSum(cArray, size);
    Complex product = ComplexProduct(cArray, size);

    std::cout << "Sum = " << sum << std::endl;
    std::cout << "Product = " << product << std::endl;

    std::cin >> ch;
    return 0;
}

ComplexArray.h

class ComplexArray
{
private:
    Complex* complexArr;
    int size;

    ComplexArray();
public:
    //Constructors and destructors
    ComplexArray(int size);
    ComplexArray(const ComplexArray& source);
    virtual ~ComplexArray();

    //Range for the complexArr
    int MaxIndex() const;

    //Overload the indexing operator
    const Complex& operator [](int index) const;
    Complex& operator [](int index);
};

ComplexArray.cpp

#include "Complex.h"
#include "ComplexArray.h"

ComplexArray::ComplexArray(int s)
{
    size = s;
    complexArr = new Complex[size];
}

ComplexArray::ComplexArray(const ComplexArray& source)
{
    //Deep copy source
    size = source.size;

    complexArr = new Complex[size];

    for (int i = 0; i < size; i++)
    {
        complexArr[i] = source.complexArr[i];
    }
}

ComplexArray::~ComplexArray()
{
    delete[] complexArr;
}

int ComplexArray::MaxIndex() const
{
    return (size - 1);
}

/*
c1.operator[](int index) should return a reference to the Complex
object, because there are two possible cases.

Case 1:
Complex c = complexArray[3];

Case 2:
complexArray[3] = c;

In the second case, complexArray[3] is an lvalue, so it must return
a Complex object  by reference, so that it can be assigned to.
*/

const Complex& ComplexArray::operator[] (int index) const
{
    return complexArr[index];
}

Complex& ComplexArray::operator[](int index)
{
    return complexArr[index];
}

complex.h

#include <iostream>

class Complex
{
private:
    double x;
    double y;
    void init(double xs, double ys); //Private helper function

public:
    //Constructors and destructors
    Complex();
    Complex(const Complex& z);
    Complex(double xs, double ys);
    virtual ~Complex();

    //Selectors
    double X() const;
    double Y() const;

    //Modifiers
    void X(double xs);
    void Y(double ys);

    //Overload binary +, = and * operators
    Complex operator + (const Complex& z);
    Complex& operator = (const Complex& z);
    Complex operator * (const Complex& z) const;

    //Overload unary - operator
    Complex operator -() const;

    friend Complex operator * (const double alpha, const Complex& z);
    friend Complex operator * (const Complex& z, const double beta);

    //Overload << operator
    friend std::ostream& operator << (std::ostream& os, const Complex& z);

    //A complex function f(z)=z^2
    Complex square();
};
4b9b3361

Ответ 1

Как вы все это указали, я пропустил прямое определение #include.

У Complex.cpp есть заголовок

#include "Complex.h"

У ComplexArray.h есть заголовок

#include "Complex.h"

У ComplexArray.cpp есть заголовок

#include "ComplexArray.h"

TestComplexNumbers.cpp имеет заголовок

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

Мои ошибки времени компиляции были решены.

Ответ 2

Я не думаю, что ошибка исходит от оператора [], как вы можете видеть в функции:

Complex ComplexSum(const ComplexArray& cArray, int size)
{
    Complex sum = cArray[0];
    for (int i = 1; i < cArray.MaxIndex(); i++)
    {
        sum = sum + cArray[i];
    }
}

Вы не возвращаете результат. Это смертельно.

Ответ 3

ComplexArray зависит от комплекса, но порядок включений не выглядит правильным

#include "ComplexArray.h"
#include "Complex.h"

Вы должны переслать-объявить Complex перед ComplexArray

 class Complex; 

Ошибка кода на \testcomplexarray.cpp строке 7, которая

 Complex sum = cArray[0];

Похоже, у вас проблемы с ctors of Complex. Убедитесь, что вы НЕ определили такие:

 Complex(Complex& v);  // that bad. it prevents to use copy constructor

Если вам нужна копия ctor по какой-то непостижимой причине, она всегда должна выглядеть так:

 Complex(const Complex& v);