Arithmetic on two CGPoints with + or - operators
Asked Answered
T

2

6

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?

Tema answered 3/8, 2013 at 20:33 Comment(2)
Yes, at least in Xcode for iOS I get the error "Invalid operands to binary expression ('CGPoint' (aka 'struct CGPoint') and 'CGPoint')"Tema
Yeah. Not possible in C. You might be able to wrangle something in C++ with operator overloading, but in general, no.Cherub
D
9

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;
}
Distant answered 3/8, 2013 at 20:47 Comment(9)
You can overload operators on structs?! I've really got to work on my C++.Shroyer
@JoshCaswell Well, structs are really the same as classes, except that they have their member visibility set to public by default.Distant
That's quite something.Shroyer
@JoshCaswell This is one of the reasons why I don't like C++: you can never know what simple operations and expressions do (even in simple cases like this) without digging through all the declarations and implementations...Distant
It comes down to discipline, I suppose. I could mess with your head by clobbering -[NSArray addObject:] with a category in ObjC, too.Shroyer
@JoshCaswell Yeah, partly. Method swizzling is used much less often in Objective-C in production code than operator overloading in C++. It's also less straightforward.Distant
Didn't work for me. I guess it's not possible in Objective-C. Question is about Objective-C, right? Why is this marked correct?Choline
@Choline This works in Objective-C++. Just give your source files a .mm extension.Kristankriste
Here's the reason operator overloading is awesome: In C#: currentVelocity = (currentVelocity - num * vector3) * d; In ObjC: *velocity= ccpMult(ccpSub(*velocity, ccpMult(vector3, num)), d);Marquess
S
3

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};
}
Shroyer answered 3/8, 2013 at 20:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.