重载运算符=问题 我写C++程序。< /P>
这是main方法的一个片段:重载运算符=问题 我写C++程序。< /P>,c++,overloading,C++,Overloading,这是main方法的一个片段: 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); 学生班在这里: #include "Student.hp
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);
学生班在这里:
#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;
}
#包括“Student.hpp”
#包括
使用名称空间std;
学生::学生(){
in=“万岁”;
}
学生::学生(串入){
这个->in=in;
}
学生:学生(const Student&orig){
}
学生::~Student(){
}
学生和学生::运算符=(学生和学生){
如果(此!=&student){
这->in=student.in;
}
归还*这个;
}
头文件位于此处:
#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 */
#包括
使用名称空间std;
#ifndef学生水电站
#定义学生HPP
班级学生{
公众:
学生();
学生(插队);
学生(const Student&orig);
虚拟~Student();
学生和运算符=(学生和学生);//重载=运算符
私人:
串入;
};
#endif/*学生水电站*/
程序的这一部分创建Student类型的数组并存储Student类型的对象。传递数组以根据冒泡排序比较值。可能有什么问题?'array'是在freestore上声明的学生数组,而不是指向学生的指针数组,因此您无法为学生分配指针,new将返回指向freestore上新位置的指针。而是将学生分配到索引位置
//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"));
std::向量数组(4,学生(“比尔·盖茨”);
向量和字符串是C++中处理数组和字符串的事实方法。
< P>除了111111的答案…< / P>代码
x+“比尔·盖茨”
正试图将char
添加到未定义的char[]
。+运算符的至少一个操作数必须已经是字符串。您可能想考虑使用<代码> x+string(“比尔盖茨”)< /COD> .< /P>注意,您的表达式<代码> x+“比尔盖茨”< /> >也不符合您的预期。它不进行字符串连接,因为两个参数都不是字符串。相反,它将指向字符数组“比尔·盖茨”的指针向前移动了与x
的代码点相同的位置(例如,对于ASCII中的x=='a'
,它将指向“比尔·盖茨”的第97个字符,这显然不存在),然后将在那里找到的任何字符解释为C字符串。如果幸运的话,您会得到一个分段错误(或您的平台的等效错误)。否则你很可能会得到垃圾。你的数组不是学生数组,而是学生数组。所以array[i]=*(新学生(x+“比尔·盖茨”)
@Yappie:无法删除该语句中new
返回的指针。每次使用它都会泄漏内存。赋值运算符需要通过常量引用或值接受它的参数。不是通过非常量引用,否则,您不能这样做:array[i]=Student()
,因为这是试图将非常量引用绑定到临时引用,这是非法的。@blastfurne:谢谢,这真是一个愚蠢的解决方案。@ucas:And?他说的远不止这些。现在我得到了这个错误:Run.cpp:In functionintmain(int,char**):Run.cpp:70:error:expected主表达式在“array”运行之前。cpp:70:error:expected
;'在第70行之前的“array”之前,您缺少一个分号,或者您有一个n个不完整的语句。这一行需要分号:std::vector array(4,student(“比尔·盖茨”);before array关键字。如果没有看到代码,就不能说包含了#include,但通常是在前面的语句格式错误时。实际上,该操作不是未定义的(但是对于程序中给定的值,它确实给出了未定义的行为,除非在具有非常不寻常的字符编码的平台上运行)x+“比尔·盖茨”
将x
转换为int
,并将数组衰减为指向第一个元素的指针,因此只有普通的指针算法。例如,如果x
是'\4'
,则学生
对象将使用字符串“l门”
初始化。
std::vector<student> array(4, student("Bill Gates"));