Я сравниваю студентов в порядке lastnamefirstnameid, но почему-то моя перегрузка не возвращает значение false для следующей основной программы, я печатаю строку comp, они такие же, я действительно смущен, где я делаю неправильно
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!!
В if (st == st2)
вы сравниваете указатели. Это, if
никогда не будет оценено как true. То, что вам действительно нужно сделать, это: if ((*st) == (*st2))
, но вы можете видеть, что вещи становятся уродливыми.
Прежде всего, нет причин использовать динамические массивы char
, а не использовать new
и delete
. Взгляните на эту переписанную версию:
class Student {
private:
std::string comp;
public:
Student(std::string last, std::string first, std::string id, ...) {
comp = last + first + id;
}
operator==(const Student& second) {
return (comp == second.comp);
}
// ...
};
int main(int, char*[]) {
Student st("last", "first", "id", "sitand", 34, 4.0, "se", "matricDate");
Student st2("last", "first", "id", "sitand", 34, 4.0, "se", "matricDate");
std::cout << "\nComp1:"<< st.getComp()<<"\n";
std::cout << "\nComp2:"<< st2.getComp()<<"\n";
if (st == st2) {
std::cout << "yes i got this body";
} else {
std::cout << "DAMNNN\n";
}
if (st.getComp() == st2.getComp())
std::cout << "yes body!!\n";
return 0;
}
Во-вторых, в качестве побочного эффекта использования new
вы просачиваете память st1
(с указанным выше кодом не происходит утечки памяти). В вашем конкретном примере это не имеет большого значения, потому что в конце выполнения программы память заявляется операционной системой, но в любой другой части программы это может быть опасно.
if(st==st2){
Вы сравниваете указатели, а не значения, поэтому перегруженный == не вызывается. В вашем случае используйте: if (* st == * st2) {
if(*st==*st2){
cout<<"yes i got this body";
}else{
cout<<"DAMNNN\n";
}
change 'if(st==st2){' to 'if(*st == *st2){'.
if(*st == *st2){
вызовет функцию bool Student::operator==(const Student &second) {
.
new
там?