gpt4 book ai didi

c++ - 重载运算符=问题

转载 作者:行者123 更新时间:2023-11-28 08:13:34 24 4
gpt4 key购买 nike

我正在编写 C++ 程序。

这是主要方法的片段:

 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 类型的对象。传递数组以根据冒泡排序比较值。可能是什么问题?

最佳答案

'array' 是在自由存储上声明的学生数组,而不是指向学生的指针数组,因此您不能将指针分配给他们,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;

最后,您将节省大量时间,如果您使用 vector 而不是 C 数组, vector 将管理它自己的内存并提供一个接口(interface)供您使用。

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

vector 和字符串实际上是在 C++ 中处理数组和字符串的方式。

关于c++ - 重载运算符=问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8376261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com