-6

For example, I'm working on an gotoIJ function, which set the pointer at the desired coordinate. I want 2 ways of passing argument into it:

  • 2 int values: gotoIJ(int i, int j)
  • a struct which store the coordinate: gotoIJ(coordinate element)

How to write it in C++? Thanks!

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Minh Nghĩa
  • 854
  • 1
  • 11
  • 28
  • 5
    What have you tried - what's stopping you from creating two gotoJ methods each of which accept the arguments you require ? – auburg Mar 30 '16 at 08:26
  • 4
    Ever heard of *function overloading*? [Find a good beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and read about it. – Some programmer dude Mar 30 '16 at 08:26

2 Answers2

4

Implement two functions:

struct Coordinate {
    int i;
    int j;
};

void gotoIJ(int i, int j) {
   // do stuff
}

void gotoIJ(const Coordinate& c) {
    gotoIJ(c.i, c.j);
}

Now clients can call:

gotoIJ(13, 42);

or:

Coordinate c1 {4, 2};
gotoIJ(c1);

See Function overloading for details.

sergej
  • 17,147
  • 6
  • 52
  • 89
0

The name of the function is not the only thing that distinguish the function itself from other functions. When you create (or better declare) a function you tell the compiler about 3 important and different points:

  • return type
  • function's name
  • parameters passed to the function

in your case you want to use the same function's name but different parameters . You can do it without problems and create those two functions as you wrote in your question.

void gotoIJ(int i, int j){
...
}

void gotoIJ(coordinate element){
...
}

I guess you don't return anything from those functions and therefore I set the returning type to void . So when in your main or anywhere else you call the function gotoIJ, the compiler will automatically call the correct one according to the parameters you pass.

Tarta
  • 1,729
  • 1
  • 29
  • 63