10
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 类,从中派生出其他更具体的材料。Material::foo() 方法表示 Material 中适用于大多数材料的方法,但有时,需要为具有不寻常属性的材料定义另一个 foo()。

我程序中的所有对象都包含一个 Material 字段。如果为它们分配了不寻常的材料,我希望调用派生的、不寻常的 foo 。

这可能很容易,或者不可能,但我无法弄清楚。

谢谢

4

2 回答 2

20

您想要的是多态性,并且要为您需要的功能启用它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"; 
    } 
}; 

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

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

int main() 
{ 
    // Unusual_Material object will be sliced!
    Material strange = Unusual_Material(); 
    strange.foo(); 
    return 0; 
} 
于 2010-11-17T20:48:29.973 回答
1

更好的解释是..

class Base
{
public:
 void foo()     //make virtual void foo(),have derived method invoked
 {
  cout << "Class Base";
 }
};
class Derived: public Base
{
public:
 void foo()
 {
  cout << "Class Derived";
 }
};
int main()
{
 Base base1 = Derived ();
 Base1.foo(); //outputs "Class Base" 
           // Base object, calling base method

 Base *base2 = new Derived ();
 Base2->foo(); //outputs"Class Base",Again Base object calling base method

// But to have base object, calling Derived method, following are the ways
// Add virtual access modifier for base foo() method. Then do as below, to //have derived method being invoked.
//
// Base *base2 = new Derived ();
// Base2->foo();    //outputs "Class Derived" .

return 0;
}
于 2013-10-17T13:27:02.977 回答