简体   繁体   中英

An issue with a non-member function

A problem I'm working on is asking me to define an istream constructor inside the class body. Let's call the class Sound. Now this constructor uses a function in its own body. But the function is supposed to be a non-member function. I have it defined in another file, but I have it declared in the header that contains the class definition itself. I've placed the header in the other file containing the non-member functions already.

The problem is, one of the parameters of the non member function has type Sound and it performs operations on the type Sound objects.

When I declare this function in the header file, if I put it before the class definition I get an error saying the objects haven't been defined.

When I put the declaration after the definition, the constructor now tells me that the function inside it's body is undefined.

If I put the declaration inside the class body, it becomes a member function.

The problem didn't explicitly state that I cannot make the function a member function so I am wondering if there is a way to overcome this catch-22.

You do not necessarily need to make the function member. You can have at least two ways to solve it in a different manner.

The problem is that you are having all this in a situation where a Sound object is not yet defined if I understand correctly.

1) You can refactor your code a bit as demonstrated below.

header file:

class Sound
{
public:
    Sound();

    doStuff();
}

cpp file:

void non_member_function(Sound sound)

Sound::Sound() { non_member_function(*this); }
Sound::doStuff() {}

void non_member_function(Sound sound) { sound.doStuff(); }

2) if you insist on the scenario aforementioned, you put a Sound sound forward declaration before the non-member function to get the type recognized. Or, you can just put the declaration after the class declaration.

header file:

class Sound
{
public:
    Sound();

    doStuff();
}

void non_member_function(Sound sound)

cpp file:

Sound::Sound() { non_member_function(*this); }
Sound::doStuff() {}

void non_member_function(Sound sound) { sound.doStuff(); }

Looks like best thing to do is to use forward declaration for class, before the function:

header:

class Sound;

void f(Sound s);

class Sound
{...};
  • In c++ you can define a function as a member function or a non-member function. If it is not specified or required that the function be define as member or non-member as you have pointed out, then I would opt for an easy or simple solution.
  • Calling a non-member function within a constructor might require you, to use a certain technic to go about this function call, now that might not be required if the function was defined as a member function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM