问题描述
以下是我的代码,
#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..
这篇关于如何使孩子的方法被调用:虚拟关键字不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!