注册 登录
编程论坛 C++教室

六百里加急:为什么在基类的get()函数前加上virual后,继承以后,在主函数中输出不是动态联编,输出的都是1呢还是,求教!谢谢啊

lianjiecuowu 发布于 2011-05-24 18:22, 518 次点击
#include<iostream>
using namespace std;
class A
{
      public:
     virtual int get(){return 1;} //难道不对吗这里?
};
class B:public A
{
      public:
      int get(){return 2;}
};
int main()
{
    while(1)
    {
    cout<<"1:父类2:子类3:退出:"<<endl;
    int choice;
    cin>>choice;
    A*p;
    bool quit =false;
    switch(1)
    {
             case 1:p=new A;
             break;
             case 2:p=new B;
             break;
             case 3:quit=true;
             break;
             default:
                     cout<<"请输入1,2,3"<<endl;
             break;
    }
    if(quit==true)
    {
                  break;
    }
    cout<<p->get()<<endl;
}
system("pause");
return 0;
}
5 回复
#2
thlgood2011-05-24 18:23
C++、面向对象
#3
buffer2011-05-24 19:13
switch(1)?? switch(choice)
#4
Pirelo2011-05-24 19:17
程序代码:
#include<iostream>
using namespace std;
class A
{
      public:
     virtual int get(){return 1;} //It's ok here:-)
};
class B:public A
{
      public:
      int get(){return 2;}
};
int main()
{
    while(1)
    {
    cout<<"1:父类2:子类3:退出:"<<endl;
    int choice;
    cin>>choice;
    A *p;
    bool quit =false;
    switch(choice)  //error writing in your code!
    {
             case 1:p=new A;
             break;
             case 2:p=new B;
             break;
             case 3:quit=true;
             break;
             default:
                    p=NULL;cout<<"请输入1,2,3"<<endl; //here is a bug in your design, pointer p is not evaluated!
             break;
    }
    if(quit==true)
    {
                  break;
    }
    if(NULL!=p)  //you'd better check p here when you using it
    {

        cout<<"the return value is: "<<p->get()<<endl;
    }

    else
    {
        cout<<"p is not evaluated!"<<endl;
    }
}
system("pause");
return 0;
}


[ 本帖最后由 Pirelo 于 2011-5-24 19:20 编辑 ]
#5
lianjiecuowu2011-05-24 22:30
回复 3楼 buffer
我写错了,不好意思哈
#6
lianjiecuowu2011-05-24 22:30
回复 4楼 Pirelo
好强
1