简体   繁体   中英

How to call a virtual void function C++?

I came across an exercise that I found online. This exercise consist of "virtual void" that I never seen before of how it works. So the exercise contain 1 header file named plans.h

namespace plans {

class HumanActions {
public:
  virtual void goTo() { }
  virtual void haveANiceColdBeer() { }
};

void applyPlan(HumanActions &actions);

}

and one cpp file

#include "Plans.h"

using plans::HumanActions;
using plans::applyPlan;

void
plans::applyPlan(HumanActions &actions) {
  actions.goTo();
  actions.haveANiceColdBeer();
}

I tried to run the function by having another main file that runs like

#include "Plans.h"

using plans::HumanActions;
using plans::applyPlan;

int main() {
    HumanActions actions;
    applyPlan(actions);
}

Unfortunately it does not run and it says that I have undefined reference to `plans::applyPlan(plans::Actions&)' so My question is how do you pass the functions for those argument given?

You have declared "void applyPlan(HumanActions &actions)" in the header file, but you have not defined (implemented) it anywhere, which is why you have the undefined symbol.

If in main(), you called applyZombiePlan() instead of applyPlan() you should be OK.

"Undefined reference" is a linker error that means the implementation for a function couldn't be found. In other words, it typically means you declared the function, and called the function, but forgot to actually write the function.

Your error message refers to plans::applyPlan(plans::Actions&) , but the closest declaration I see is void applyPlan(HumanActions &actions); , which has a different argument type. Assuming this isn't just a mix-up between different versions of the code in your post, you might have accidentally declared two different applyPlan functions but only implemented one of them.

If your program consists of more than one .cpp file, another possible reason is that you're accidentally trying to compile and link a single file as if it were a complete program instead of linking all the modules together. That'd make the linker not see anything defined in the other .cpp files. If you're a beginner, your best bet is to compile all your source files at once with a single command line, eg g++ *.cpp -o myprog .

Calling a virtual function is no different from calling a regular function, BTW, and applyPlan is not a virtual function anyway.

I think you can make use of extern keyword. whenever you are actually defining your global function, you can say void XYZ(){} and everywhere else you can say extern void XYZ().

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