虚方法问题 [英] Virtual Methods Question

查看:63
本文介绍了虚方法问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下三个班级


A级

{

公开:

virtual void f()= 0;

};


B级:公共A

{

public:

virtual void f();

};


void B :: f()

{

cout<< B :: f();

}


C级:公共B

{

public:

void f();

};


void C :: f()

{

cout<< C :: f()" ;;

}

main()

{

A * x = new C();


x-> f();

}


以上程序打印如下:


B :: f()


但是,我希望程序打印

C :: f()


为什么程序会这样做?有没有办法让我调用C'的f()

方法而不是B'的f()方法?我正在使用GNU编译器

用于VxWorks 5.5。在此先感谢您的帮助。

-Daniel

I have the following three classes

class A
{
public:
virtual void f() = 0;
};

class B: public A
{
public:
virtual void f();
};

void B::f()
{
cout << "B::f()";
}

class C: public B
{
public:
void f();
};

void C::f()
{
cout << "C::f()";
}
main()
{
A* x = new C();

x->f();
}

The above program prints the following:

B::f()

But, I wanted the program to print

C::f()

Why is the program doing this? Is there any way for me to have C''s f()
method invoked instead of B''s f() method? I am using the GNU compiler
for VxWorks 5.5. Thanks in advance for any help.
-Daniel

推荐答案



Daniel写道:

Daniel wrote:
上面的程序打印如下:

B :: f()

但是,我想要程序打印

C :: f()
The above program prints the following:

B::f()

But, I wanted the program to print

C::f()




打印" C :: f()"在这里。这应该是它应该做的。



prints "C::f()" over here. That is what it should do.




Daniel <哒*********** @ gmail.com> schrieb im Newsbeitrag

新闻:11 ********************** @ v46g2000cwv.googlegr oups.com ......

"Daniel" <da***********@gmail.com> schrieb im Newsbeitrag
news:11**********************@v46g2000cwv.googlegr oups.com...
C类:公共B
{
公开:
void f();
};
class C: public B
{
public:
void f();
};



你错过了那里的虚拟。


f~



you miss a virtual there.

f~




Frank施密特" < fs@example.com>在留言中写道

新闻:dt ********** @ online.de ...

|

| "丹尼尔" <哒*********** @ gmail.com> schrieb im Newsbeitrag

|新闻:11 ********************** @ v46g2000cwv.googlegr oups.com ...

|

| > C级:公共B

| > {

| >公众:

| > void f();

| > };

|

|你错过了那里的虚拟。

|

| f~

|


不,如果纯抽象或基类指定void f()是虚拟的那么

那么它在整个层次结构中是虚拟的。无论派生的

类是否具有虚函数。


"Frank Schmidt" <fs@example.com> wrote in message
news:dt**********@online.de...
|
| "Daniel" <da***********@gmail.com> schrieb im Newsbeitrag
| news:11**********************@v46g2000cwv.googlegr oups.com...
|
| > class C: public B
| > {
| > public:
| > void f();
| > };
|
| you miss a virtual there.
|
| f~
|

Nope, if the pure-abstract or base class specifies that void f() is virtual
then its virtual in the entire hierarchy. Regardless whether the derived
classes have that function as virtual or not.


这篇关于虚方法问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆