简体   繁体   中英

C++ Polymorphism / Pointers - expression must have a constant value

I am new to Polymorphism and Templates in C++, and I came accross the error: "expression must have a constant value" when using the pointer of Dad , what is the problem?

#include <iostream>
class Animal{
public:
    std::string noise;
    virtual void speak(char* message){
        std::cout << message << " " << noise.c_str() << std::endl;
    }
};
template <Animal* Parent> class Baby : public Animal{
public:
    void speak(char* message){
        std::cout << message << " " << Parent->noise.c_str() << Parent->noise.c_str() << std::endl;
    }
};
int main(void){
    Animal Dog;
    Dog.noise = "WOOF";
    Animal* Dad = &Dog;
    Baby<Dad> puppy; // Error here
    Dad->speak("I am a dog");
    puppy.speak("I am a puppy");
    return (0);
}

Wanted output:

I am a dog WOOF

I am a puppy WOOFWOOF

When I tried to run, I got the error: error C2971: 'Baby' : template parameter 'Parent' : 'Dad' : a local variable cannot be used as a non-type argument

You cannot use local pointer as template parameter, as sayed in message. You can use something like

class Animal{
public:
    std::string noise;
    void speak(char* message)
    {
        std::cout << message << " " << noise.c_str() << std::endl;
    }
};
class Baby
{
public:
    Baby(Animal* parent) : parent_(parent) {}
    void speak(char* message)
    {
        std::cout << message << " " <<
        parent->noise.c_str() << parent->noise.c_str() << std::endl;
    }
private:
   Animal* parent_;
};

and you do not need inheritance in this case.

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