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()。
我程序中的所有对象都包含一个Material字段。如果他们被分配了一个不寻常的材料,我希望调用派生的,不寻常的foo。
这可能要么很简单,要么不可能,但无论如何我无法弄明白。
由于
答案 0 :(得分: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;
}
您的代码段中的内容为slice the Unusual_Material
object:
int main()
{
// Unusual_Material object will be sliced!
Material strange = Unusual_Material();
strange.foo();
return 0;
}
答案 1 :(得分: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;
}