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

关于多态还有虚函数的问题,求帮忙改正,谢谢

菜鸟1234 发布于 2013-09-03 15:51, 551 次点击
#include<iostream>
using namespace std;
class X1
{
protected:
    int x;
public:
    X1(int xx){x=xx;}
    virtual void output()=0;
};
class Y1:private X1
{
    int y;
public:
    Y1(int xx=0,int yy=0):X1(xx)
    {y=yy;}
void output()
    {
        cout<<"x="<<x<<",y="<<y<<endl;
    }
};
class Z1:protected X1
{
    int z;
public:
    Z1(int xx=0,int zz=0):X1(xx)
    { z=zz;}
     void output()
    {
        cout<<"x="<<x<<",z"<<z<<endl;
    }
};
int main()
{
    X1 a(2);
    Y1 b(3,4);
    Z1 c(5,6);
    X1*p[3]={&a,&b,&c};
    for(itn i=0;i<3;i++)
    {
        p[i]->output();
    }
    return 0;
}
求帮忙改正
5 回复
#2
rjsp2013-09-03 16:20
改正什么呀,你自己不说清楚。
另外,看你的代码,对C++那是毫无概念,建议你先看一遍《Effective C++》,了解 private/protected继承的逻辑含义
#3
peach54602013-09-03 17:45
先把问题描述清楚
#4
菜鸟12342013-09-03 21:14
回复 2楼 rjsp
额,这个本来就是改错题的,让你纠正的。。
#5
菜鸟12342013-09-03 21:15
回复 3楼 peach5460
就是改正里面的错误里
#6
toofunny2013-09-04 01:24
错漏百出啊,完全无视类的继承规则,代码修改如下,VC6编译通过。

#include<iostream>
using namespace std;
class X1
{
protected:
    int x;
public:
    X1(int xx){x=xx;}
    virtual void output() = 0;
};
class Y1:public X1
{
    int y;
public:
    Y1(int xx=0,int yy=0):X1(xx)
    {y=yy;}
void output()
    {
        cout<<"x="<<x<<",y="<<y<<endl;
    }
};
class Z1:public X1
{
    int z;
public:
    Z1(int xx=0,int zz=0):X1(xx)
    { z=zz;}
     void output()
    {
        cout<<"x="<<x<<",z="<<z<<endl;
    }
};
int main()
{
//    X1 a(2);
    Y1 b(3,4);
    Z1 c(5,6);
    X1*p[3]={  &b,&c};
    for(int i=0;i<2;i++)
    {
        p[i]->output();
    }
    return 0;
}
1