C++ 执行输入检查并初始化C++;
我有一个示例代码,要求用户按用户输入动物,但检查在if-else构造中,编译器给我错误“error:'animal'未在作用域中声明”。这是我的密码。请建议我如何解决这个问题C++ 执行输入检查并初始化C++;,c++,object,if-statement,C++,Object,If Statement,我有一个示例代码,要求用户按用户输入动物,但检查在if-else构造中,编译器给我错误“error:'animal'未在作用域中声明”。这是我的密码。请建议我如何解决这个问题 class Animal{ public: string getName(){ return myName; } void setName(string name){ myName = name; } virtual string Sound()
class Animal{
public:
string getName(){
return myName;
}
void setName(string name){
myName = name;
}
virtual string Sound()
{
}
private:
string myName;
};
class Cat : public Animal{
public:
string Sound(){
return "Myau!\n";
}
};
class Dog : public Animal{
public:
string Sound(){
return "Bark!\n";
}
};
int main() {
string type, name;
cout<<"Vyvedete jivotno:\n 1. Cat\n2. Dog\nJivotno:";
cin>>type;
cout<<"\nVyvedete ime:";
cin>>name;
if(type == "Cat")
{
Cat animal;
}
else if(type == "Dog")
{
Dog animal;
}
animal.setName(name);
cout<<"My name is "<<animal.getName()<<endl;
cout<<animal.Sound()<<endl;
return 0;
}
类动物{
公众:
字符串getName(){
返回我的名字;
}
void setName(字符串名称){
我的名字=名字;
}
虚拟字符串声音()
{
}
私人:
字符串myName;
};
猫类:公共动物{
公众:
弦音{
返回“Myau!\n”;
}
};
犬类:公共动物{
公众:
弦音{
返回“树皮!\n”;
}
};
int main(){
字符串类型、名称;
couttype;
coutname;
如果(类型=“Cat”)
{
猫科动物;
}
else if(类型==“狗”)
{
犬类动物;
}
动物名称(名称);
库特
在这个范围内本地创建一个Cat
对象if(type==“Cat”){…}
。并且您不能创建类似于其他语言的东西
Animal animal;
if (type == "Cat") {
animal = Cat();
}
这将创建一个Cat
对象,并将其复制到Animal
对象中,有时称之为“切片”,仅复制Cat
对象的一部分
它是如何工作的
Animal
有这样一个隐式生成的复制构造函数
Animal(const Animal &original) {
// Copies here
}
所以,将猫复制到动物身上,只是将原始的
视为一只动物,这是复制的
如果你试图做参考,它将不起作用,为什么
Animal &animal;
现在,这个对象没有初始化(不允许空引用)
如果你尝试这样做:
Animal &animal = Animal();
Animal source;
Animal &animal = source;
if(type == "Cat")
{
Cat catSource;
animal = catSource;
}
else if(type == "Dog")
{
Dog dogSource;
animal = dogSource;
}
您不能这样做,因为Animal()
是一个临时对象(不能被普通引用引用(在C++11中调用:lvalue reference
)引用)
“临时对象”不能与“本地对象”混淆,临时对象是由表达式生成的对象,如Cat()
。但本地对象是范围内的任何对象
然后,试着做这样的事情:
Animal &animal = Animal();
Animal source;
Animal &animal = source;
if(type == "Cat")
{
Cat catSource;
animal = catSource;
}
else if(type == "Dog")
{
Dog dogSource;
animal = dogSource;
}
它将尝试使用复制赋值
,这类似于复制构造函数,但用于现有对象(因此也会发生切片)
这样,您的解决方案是在(C++)中使用指针(使用智能指针为您自动管理),而不是本地对象。
std::unique_ptr<Animal> animal;
if (type == "Cat") {
animal = std::unique_ptr(new Animal());
}
您的动物在if语句内声明,if语句外没有动物。您创建的
Cat
和Dog
在您创建的作用域结束后将被销毁。这些Cat
和Dog
对象的生存期是什么?您也不需要所有这些代码来查看问题:int main(){int i=10;{int x=20;}x=4;}
--x
在x=4;
代码行不再有效。Cat animal在if{}块中声明,因此它只存在于那里。Dog animal是在else if{}块中声明的单独对象,因此它只存在于那里。在if{}else if{}之后,这两个变量都超出范围。请记住,local
变量对其范围可见,因此超出范围的变量不可用。