虚拟关键字不起作用

虚拟关键字不起作用

本文介绍了如何使孩子的方法被调用:虚拟关键字不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的代码,

#include<iostream>
#include<string>

using namespace std;

class TestClass
{
  public:
    virtual void test(string st1, string st2);

};

class ExtendedTest: public TestClass
{
  public:
    virtual void test(string st1, string st2);
};

void TestClass::test(string st1, string st2="st2")
{
     cout << st1 << endl;
     cout << st2 << endl;
}

void ExtendedTest::test(string st1, string st2="st2")
{
     cout << "Extended: " << st1 << endl;
     cout << "Extended: " << st2 << endl;
}

void pass(TestClass t)
{
    t.test("abc","def");
}


int main()
{
   ExtendedTest et;
   pass(et);
   return 0;
}

运行代码时,将调用基类的method('test').但是我希望调用child方法是因为我将方法指定为虚函数.

然后如何使子类的方法被调用?谢谢.

解决方案
void pass(TestClass t)
{
    t.test("abc","def");
}

执行此操作时,将传递的对象切片TestClass中,它的身份已丢失,因此它现在的行为类似于TestClass并相应地调用该方法.

要解决此问题,您想通过引用传递t,如@Nick所建议,或(不建议)通过指针传递.现在,只要test被标记为虚拟

,它便会保留其身份并调用适当的功能.

固定拼接->切成薄片.

The following is my code,

#include<iostream>
#include<string>

using namespace std;

class TestClass
{
  public:
    virtual void test(string st1, string st2);

};

class ExtendedTest: public TestClass
{
  public:
    virtual void test(string st1, string st2);
};

void TestClass::test(string st1, string st2="st2")
{
     cout << st1 << endl;
     cout << st2 << endl;
}

void ExtendedTest::test(string st1, string st2="st2")
{
     cout << "Extended: " << st1 << endl;
     cout << "Extended: " << st2 << endl;
}

void pass(TestClass t)
{
    t.test("abc","def");
}


int main()
{
   ExtendedTest et;
   pass(et);
   return 0;
}

When I run the code, the method('test') of base class is called.But I expect the method of child is called because I specified methods as virtual function.

Then how can I make method of child class be called ? Thank you.

解决方案
void pass(TestClass t)
{
    t.test("abc","def");
}

When you do this, the object you are passing gets sliced into a TestClass and its identity is lost, so it now behaves like a TestClass and calls the method accordingly.

To Fix this you want to pass t by reference as @Nick suggested, or (not recommended) by pointer. It will now retain its identity and call the appropriate function, as long as test is marked virtual

Edit: fixed spliced -> sliced .. too much bioshock..

这篇关于如何使孩子的方法被调用:虚拟关键字不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:29