将类成员传递给void*

snr*_*snr 0 c++ void-pointers

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

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

testClass obj[3];
obj[0].set(1,1);
obj[1].set(2,1);
obj[2].set(1,1);
Run Code Online (Sandbox Code Playgroud)

首先,我试过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
}
Run Code Online (Sandbox Code Playgroud)

我这么想,但我无法解决这个问题.我想比较一下

obj[0].getDay() == obj[1].getDay();
obj[0].getMonth() == obj[1].getMonth();
Run Code Online (Sandbox Code Playgroud)

通过传递.

mad*_*uri 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);
}
Run Code Online (Sandbox Code Playgroud)

然后,你可以像这样比较:

DayOfYear day1;
DayOfYear day2;
// ...
if (day1 == day2)  // syntactically equivalent to to: if (day1.operator==(day2))
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

编辑:因为你不想使用运算符重载,你总是可以使用这样的函数/静态方法:

bool compareDates(const DayOfYear& day1, const DayOfYear& day2)
{
    return (day1.getMonth() == day2.getMonth()) && (day1.getDay() == day2.getDay());
}
Run Code Online (Sandbox Code Playgroud)

然后,比较如下:

DayOfYear day1;
DayOfYear day2;
// ...
if (compareDates(day1, day2))
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • @itsnotmyrealname:为什么不能使用它?这是正确的解决方案. (2认同)