Оператор перегрузки = проблема - PullRequest
0 голосов
/ 04 декабря 2011

Я пишу программу на С ++.

Это фрагмент основного метода:

 Student * array = new Student[4];

    int i = 0;

    for(char x = 'a'; x < 'e'; x++){        

       array[i] = new Student(x+" Bill Gates");
        i++;
    }
    defaultObject.addition(array, 4);

Эта строка array[i] = new Student(x+" Bill Gates"); выдает ошибку:

g++    -c -g -MMD -MP -MF build/Debug/Cygwin-Windows/Run.o.d -o build/Debug/Cygwin-Windows/Run.o Run.cpp
In file included from Run.cpp:12:
Assessment3.hpp:53:39: warning: no newline at end of file
Run.cpp: In function `int main(int, char**)':
Run.cpp:68: error: no match for 'operator=' in '*((+(((unsigned int)i) * 8u)) + array) = (string(((+((unsigned int)x)) + ((const char*)" Bill Gates")), ((const std::allocator<char>&)((const std::allocator<char>*)(&allocator<char>())))), (((Student*)operator new(8u)), (<anonymous>->Student::Student(<anonymous>), <anonymous>)))'
Student.hpp:19: note: candidates are: Student& Student::operator=(Student&)
make[2]: Leaving directory `/cygdrive/g/Aristotelis/C++/assessment3'
make[1]: Leaving directory `/cygdrive/g/Aristotelis/C++/assessment3'
make[2]: *** [build/Debug/Cygwin-Windows/Run.o] Error 1
make[1]: *** [.build-conf] Error 2
make: *** [.build-impl] Error 2

BUILD FAILED (exit value 2, total time: 3s)

Здесь находится студенческий класс:

#include "Student.hpp"
#include <string>
using namespace std;

Student::Student(){
    in = "hooray";
}

Student::Student(string in) {
    this -> in = in;
}

Student::Student(const Student& orig) {
}

Student::~Student() {
}
Student & Student::operator=(Student & student){
    if(this != &student){
        this->in = student.in;
    }
    return *this;
}

Заголовочный файл находится здесь:

#include <string>
using namespace std;

#ifndef STUDENT_HPP
#define STUDENT_HPP

class Student {
public:
    Student();
    Student(string in);
    Student(const Student& orig);
    virtual ~Student();
    Student & operator=(Student & student); // overloads = operator
private:
    string in;
};

#endif  /* STUDENT_HPP */

Эта часть программы создает массив типа Student и хранит объекты типа student. Массив передается для сравнения значений по пузырьковой сортировке. В чем может быть проблема?

Ответы [ 2 ]

1 голос
/ 04 декабря 2011

'массив' - это массив учеников, объявленный в бесплатном хранилище, а не массив указателей на учеников, поэтому вы не можете назначить им указатель, new возвращает указатель на новое место в бесплатном хранилище.Вместо этого вы назначаете студента в индексированное местоположение.

//no new, you are assigning to a memory block already on the 
array[i]=student("bob");

Также, пока я здесь, вы не можете объединить строку C и символ, подобный этому.Тем не менее, вы можете использовать std :: string для выполнения этой тяжелой работы.

char x='a';
std::string bill("bill gates");
std::string temp=bill+x;

Наконец, вы сэкономите много времени, если вы используете вектор вместо массива C, вектор будет управлять своей собственной памятьюи предоставляет интерфейс для использования.

std::vector<student> array(4, student("Bill Gates"));

Векторы и строка - это де-факто способ работы с массивами и строками в c ++.

0 голосов
/ 04 декабря 2011

В дополнение к ответу 111111 ...

Код x+" Bill Gates" пытается добавить char к char[], который не определен. По крайней мере, один из операндов оператора + должен быть строкой. Вы можете рассмотреть возможность использования x + string(" Bill Gates").

...