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?

jscs
  • 63,694
  • 13
  • 151
  • 195
ndomin
  • 428
  • 4
  • 11
  • Yes, at least in Xcode for iOS I get the error "Invalid operands to binary expression ('CGPoint' (aka 'struct CGPoint') and 'CGPoint')" – ndomin Aug 03 '13 at 20:38
  • 3
    Yeah. Not possible in C. You might be able to wrangle something in C++ with operator overloading, but in general, no. – ipmcc Aug 03 '13 at 20:38

2 Answers2

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;
}
  • 1
    You can overload operators on `struct`s?! I've really got to work on my C++. – jscs Aug 03 '13 at 20:50
  • 2
    @JoshCaswell Well, `struct`s are really the same as `class`es, except that they have their member visibility set to `public` by default. –  Aug 03 '13 at 20:51
  • That's quite something. – jscs Aug 03 '13 at 20:52
  • 1
    @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... –  Aug 03 '13 at 20:53
  • It comes down to discipline, I suppose. I could mess with your head by clobbering `-[NSArray addObject:]` with a category in ObjC, too. – jscs Aug 03 '13 at 20:55
  • 1
    @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. –  Aug 03 '13 at 20:57
  • 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? – Jonny Mar 20 '15 at 05:37
  • @Jonny This works in Objective-C++. Just give your source files a .mm extension. – Marcelo Cantos Dec 26 '15 at 05:31
  • 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);` – Jason Knight Sep 28 '17 at 22:38
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};
}
jscs
  • 63,694
  • 13
  • 151
  • 195