将 class 成员传递给 void*

passing class members to void*

class testClass
{
public:
    void set(int monthValue, int dayValue);
    int getMonth( );
    int getDay( );
private:
    int month;
    int day;
};

我有一个简单的 class,如上所示。我尝试将它的对象传递给一个检查它们是否相等的函数。

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();

路过。

将此 (public) 方法添加到您的 class 怎么样?

// 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))
{
    // ...
}

编辑:因为你不想使用运算符重载,你总是可以用这样的function/static方法来做到这一点:

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))
{
    // ...
}

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

#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;
}

在您编写的 compare_class 函数中,您正在比较实际对象的地址。这在对象平等方面没有任何意义。函数return应该是什么?如果对象相等?它的写法是:如果对象的位置不同 - return true;如果位置相同 - return false,这与您想要的相反。

由于您没有在 class 中使用任何指针,并且不想使用运算符重载,请查看 memcmp。用法如下:

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