문제

In Objective-C I'm starting to work with CGPoints and when I need to add two of them the way I'm doing it is this:

CGPoint p1 = CGPointMake(3, 3);
CGPoint p2 = CGPointMake(8, 8);
CGPoint p3 = CGPointMake(p2.x-p1.x, p2.y-p1.y);

I would like to be able to just do:

CGPoint p3 = p2 - p1;

Is that possible?

도움이 되었습니까?

해결책

And here's the "something" that @ipmcc suggested: C++ operator overloading. Warning: do not do this at home.

CGPoint operator+(const CGPoint &p1, const CGPoint &p2)
{
    CGPoint sum = { p1.x + p2.x, p1.y + p2.y };
    return sum;
}

다른 팁

You can't use arithmetic operators on structs, unfortunately. The best you can do is a function:

CGPoint NDCGPointMinusPoint(CGPoint p1, CGPoint p2)
{
    return (CGPoint){p1.x-p2.x, p1.y-p2.y};
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top