关于虚函数的有关问题
关于虚函数的问题
#include <iostream.h>
class X1
{
int x;
public:
X1(int xx=0){x=xx;}
virtual void output()
{
cout < < "x= " < <x < <endl;
}
};
class Y1:public X1
{
int y;
public:
Y1(int xx=0,int yy=0):X1(xx){y=yy;}
virtual void ouput()
{
X1::output();
cout < < "y= " < <y < <endl;
}
};
void show1(X1 *p)
{
p-> output();
}
void show2(X1 &p)
{
p.output();
}
void main()
{
X1 a(5);
Y1 b(6,7);
show1(&a);show1(&b);
show2(a);show2(b);
}
执行结果
x=5
x=6
x=5
x=6
为什么没有执行y=???
------解决方案--------------------
class A
{
public:
virtual void show()
{
cout < < 3 < < endl;
}
};
class B:public A
{
public:
virtual void show()
{
cout < < 33 < < endl;
}
};
void fun(A &ra)
{
ra.show();
}
int main()
{
A a;
B b;
fun(a);
fun(b);
return 0;
}
------解决方案--------------------
virtual void output()
virtual void ouput()
===========
output即可以,呵呵^_^,okokok
------解决方案--------------------
因为你的 X1 中虚函数叫 output(), 而你的 Y1 中重载的叫 ouput(), 少了一个 "t " 啊,大佬
------解决方案--------------------
函数名根本不一样,没构成虚函数
#include <iostream.h>
class X1
{
int x;
public:
X1(int xx=0){x=xx;}
virtual void output()
{
cout < < "x= " < <x < <endl;
}
};
class Y1:public X1
{
int y;
public:
Y1(int xx=0,int yy=0):X1(xx){y=yy;}
virtual void ouput()
{
X1::output();
cout < < "y= " < <y < <endl;
}
};
void show1(X1 *p)
{
p-> output();
}
void show2(X1 &p)
{
p.output();
}
void main()
{
X1 a(5);
Y1 b(6,7);
show1(&a);show1(&b);
show2(a);show2(b);
}
执行结果
x=5
x=6
x=5
x=6
为什么没有执行y=???
------解决方案--------------------
class A
{
public:
virtual void show()
{
cout < < 3 < < endl;
}
};
class B:public A
{
public:
virtual void show()
{
cout < < 33 < < endl;
}
};
void fun(A &ra)
{
ra.show();
}
int main()
{
A a;
B b;
fun(a);
fun(b);
return 0;
}
------解决方案--------------------
virtual void output()
virtual void ouput()
===========
output即可以,呵呵^_^,okokok
------解决方案--------------------
因为你的 X1 中虚函数叫 output(), 而你的 Y1 中重载的叫 ouput(), 少了一个 "t " 啊,大佬
------解决方案--------------------
函数名根本不一样,没构成虚函数