2013-11-22 126 views
0

我在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!! 
+0

當然,你正在泄漏記憶。你爲什麼在那裏使用'new'? – Shoe

回答

0
if(st==st2){ 

你比較指針沒有值,因此重載==不叫。在你的情況下使用: 如果(* ST == * ST2){

0
change `if(st==st2){` to `if(*st == *st2){`. 

if(*st == *st2){將調用函數bool Student::operator==(const Student &second) {

0
if(*st==*st2){ 
     cout<<"yes i got this body"; 
    }else{ 
     cout<<"DAMNNN\n"; 
    } 
0

if (st == st2)您正在比較指針。 if永遠不會被評估爲真。你實際需要做的是:if ((*st) == (*st2)),但你可以看到事情變得越來越難看。

首先沒有理由使用動態char陣列,而不是使用newdelete。看看這個,而不是改寫版本:

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記憶的副作用(與上面的代碼,沒有內存泄漏)。在你的具體例子中,這並不重要,因爲在程序執行結束時,操作系統會聲明內存,但在程序的其他任何部分都可能會有危險。