运算符重载c == isEqual

时间:2013-11-22 01:51:02

标签: c++

我在lastnamefirstnameid顺序比较学生,但不知怎的,我的重载失败,它返回以下主程序的假值,我打印字符串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!!

4 个答案:

答案 0 :(得分:0)

if(st==st2){

比较指针而不是值,因此不会调用重载==。在你的情况下使用:     if(* st == * st2){

答案 1 :(得分:0)

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

if(*st == *st2){会调用函数bool Student::operator==(const Student &second) {

答案 2 :(得分:0)

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

答案 3 :(得分: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的内存(使用上面的代码,没有内存泄漏)。在您的具体示例中,它并不重要,因为在程序执行结束时,操作系统会声明内存,但在程序的任何其他部分中,它可能是危险的。