2015-10-19 35 views
-1
class testClass 
{ 
public: 
    void set(int monthValue, int dayValue); 
    int getMonth(); 
    int getDay(); 
private: 
    int month; 
    int day; 
}; 

我有一個簡單的類,可以在上面看到。我試圖將它的對象傳遞給一個檢查它們是否相等的函數。傳遞類成員void *

testClass obj[3]; 
obj[0].set(1,1); 
obj[1].set(2,1); 
obj[2].set(1,1); 

首先,我試着像cout << (obj[0] == obj[1]);,但也不是沒有可能運算符重載,使用模板等,所以,我可以用他們做,但我怎麼能傳遞成員變量的void*功能?

bool cmp_testClass(void const *e1, void const *e2) 
{ 
    testClass* foo = (testClass *) e1; 
    testClass* foo2 = (testClass *) e2; 
    return foo - foo2; // if zero return false, otherwise true 
} 

我以爲這樣想,但我無法解決問題。我想比較像

obj[0].getDay() == obj[1].getDay(); 
obj[0].getMonth() == obj[1].getMonth(); 

通過。

+1

究竟是什麼問題?我不明白你的問題。 –

+1

這裏絕對不需要'void *'。你的'compare_class'可以使用'const DayOfYear&',但是你可能需要使用public getters或者使這個函數成爲'friend'。 – crashmstr

+2

如果您不想通過'foo-foo2'進行比較,那麼請執行其他操作。我非常懷疑,無論你想要做什麼都應該以需要無效指針的方式完成。 – Hurkyl

回答

0

在compare_class功能,那你寫,你是比較實際的對象的地址。這在對象平等方面並不意味着什麼。函數應該返回什麼?如果對象相同?它的寫法是:如果對象的位置不同 - 返回true;如果位置相同 - 返回false,與您想要的極性相反。

既然您沒有在您的班級內使用任何指針,也不想使用操作符重載,請查看memcmp。用法如下:

if (0 == memcmp (&obj[0], &obj[1], sizeof (obj[0])) 
    { 
    // Do stuff. 
    } 
+3

你正在認真地向一個初學者推薦'memcmp',它已經在所有指針廢話的錯誤軌道上?哇。僅僅因爲你是第一個提到身份與平等之間的區別的人,就不會屈服於投票。 –

+0

@ChristianHackl他明確表示他希望比較2個對象而不使用運算符重載。從我所看到的每一個建議都是以某種方式或另一種方式 - 與運營商超載有關。這個解決方案沒有使用操作符重載,所以我認爲這是OPs問題的直接答案。 –

6

如何將此(公共)方法添加到您的班級?

// overloading the "==" comparison operator (no templates required in this particular case 
bool operator==(const DayOfYear& otherDay) const 
{ 
    return (month == otherDay.month) && (day == otherDay.day); 
} 

然後,你可以比較像這樣:

DayOfYear day1; 
DayOfYear day2; 
// ... 
if (day1 == day2) // syntactically equivalent to to: if (day1.operator==(day2)) 
{ 
    // ... 
} 

編輯:既然你不想使用操作符重載,你可以隨時使用這樣的功能/靜態方法做:

bool compareDates(const DayOfYear& day1, const DayOfYear& day2) 
{ 
    return (day1.getMonth() == day2.getMonth()) && (day1.getDay() == day2.getDay()); 
} 

於是,比較如下:

DayOfYear day1; 
DayOfYear day2; 
// ... 
if (compareDates(day1, day2)) 
{ 
    // ... 
} 
+0

@itsnotmyrealname然後,如果你確定它成功了,就施放。 –

+0

@itsnotmyrealname:檢查編輯 – 865719

+2

@itsnotmyrealname:爲什麼你不能使用它?這是正確的解決方案。 –

0

您可以在類中添加好友功能:

#include <iostream> 
using namespace std; 
class DayOfYear 
{ 
public: 
void set(int monthValue, int dayValue) { 
    month = monthValue; 
    day = dayValue; 
} 

friend bool compare(DayOfYear&d1,DayOfYear&d2) { 

    return (d1.getDay() == d2.getDay()) && (d1.getMonth() == d2.getMonth()); 
} 

int getMonth() { return month; } 

int getDay() { return day; } 

private: 
int month; 
int day; 
}; 

int main(){ 

DayOfYear obj[3]; 
obj[0].set(1,1); 
obj[1].set(1,1); 
obj[2].set(1,1); 


if(compare(obj[0],obj[1])){ 
    cout<<"Match"<<endl; 
} 


return 0; 
}