我在lastnamefirstnameid順序比較學生,但不知何故我的重載失敗它返回以下主要程序的false值,我打印字符串comp他們是相同的,我真的很困惑我在哪裏做錯運算符重載c == isEqual
bool Student::operator==(const Student &second) {
if(strcmp(comp,second.comp)==0){
return true;
}else{
return false;
}
}:
comp=new char[strlen(fName)+strlen(lName)+strlen(id)+1];
sprintf(comp,"%s%s%s",lName,fName,id);
#include<iostream>
#include<string.h>
#include"Student.cpp"
#include<stdio.h>
using namespace std;
int main(){
Student *st=new Student("last", "first", "id", "sitand", 34, 4.0, "se", "matricDate");//=new Student();
Student *st2=new Student("last", "first", "id", "sitand", 34, 4.0, "se", "matricDate");//=new Student();
st->toString();
cout<<"\nComp1:"<<st->getComp()<<"\n";
cout<<"\nComp2:"<<st2->getComp()<<"\n";
if(st==st2){
cout<<"yes i got this body";
}else{
cout<<"DAMNNN\n";
}
if(strcmp(st->getComp(),st2->getComp())==0){
cout<<"yes body!!\n";
}
delete st;
return 0;
};
這是輸出:
Name:first
Last Name:last
id:id
Standing:sitand
GPA:4
Date of birth:se
Matriculation Date:matricDate
Comp1:lastfirstid
Comp2:lastfirstid
DAMNNN
yes body!!
當然,你正在泄漏記憶。你爲什麼在那裏使用'new'? – Shoe