[英]C++ Polymorphism / Pointers - expression must have a constant value
我是C ++中的多态和模板的新手,遇到了一个错误:使用Dad
的指针时,“表达式必须具有恒定值”,这是什么问题?
#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);
}
想要的输出:
我是狗WOOF
我是小狗WOOFWOOF
当我尝试运行时,出现错误: error C2971: 'Baby' : template parameter 'Parent' : 'Dad' : a local variable cannot be used as a non-type argument
您不能使用本地指针作为模板参数,如消息中所述。 您可以使用类似
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_;
};
在这种情况下,您不需要继承。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.