从基类引用调用派生类方法 [英] Call derived class method from base class reference

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

问题描述

class Material
{
public:
 void foo()
 {
  cout << "Class Material";
 }
};

class Unusual_Material : public Material
{
public:
 void foo()
 {
  cout << "Class Unusual_Material";
 }
};

int main()
{
 Material strange = Unusual_Material();
 strange.foo(); //outputs "Class Material" 

 return 0;
}



我希望这会导致Class Unusual_Material控制台。有没有办法,我可以实现这一点?在我的程序中,我有一个类材料从其他更具体的材料派生。方法Material :: foo()代表了一种适用于大多数材料的Material中的方法,但是在某种情况下,需要为具有不寻常属性的材质定义另一个foo()。

I would like for this to result in the "Class Unusual_Material" being displayed to the console. Is there a way I can achieve this? In my program I have a class Material from which other more specific materials are derived. The method Material::foo() represents a method in Material that is adequate for most materials, but occationally, another foo() needs to be defined for a material with unusual properties.

我程序中的所有对象都包含一个材质字段。如果他们被分配了一个不寻常的材料,我想得到的,不寻常的foo被调用。

All objects in my program contain a Material field. In the event that they are assigned an unusual material, I would like the derived, unusual foo to be called.

这可能是很容易或不可能,但我

This is probably either pretty easy, or impossible, but I can't figure it out either way.

感谢

推荐答案

你想要的是多态性,并为它启用一个函数,你需要使它 virtual

What you want is polymorphism, and to enable it for a function you need to make it virtual:

class Material 
{ 
public: 
    virtual void foo() // Note virtual keyword!
    { 
        cout << "Class Material"; 
    } 
}; 

class Unusual_Material : public Material 
{ 
public: 
    void foo() // Will override foo() in the base class
    { 
        cout << "Class Unusual_Material"; 
    } 
}; 

此外,多态仅适用于引用和指针:

Also, polymorphism only works for references and pointers:

int main()  
{  
    Unusual_Material unusualMaterial;
    Material& strange = unusualMaterial;
    strange.foo();  
    return 0; 
}

/* OR */

int main()  
{  
    Unusual_Material unusualMaterial;
    Material* strange = &unusualMaterial;
    strange->foo();  
    return 0; 
}

您的代码段中有什么切换 Unusual_Material 对象

What you have in your code snippet will slice the Unusual_Material object:

int main() 
{ 
    // Unusual_Material object will be sliced!
    Material strange = Unusual_Material(); 
    strange.foo(); 
    return 0; 
} 

这篇关于从基类引用调用派生类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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