且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C ++中找到对象的类型?

更新时间:2023-02-26 18:48:11

也请参阅 ^ ].


您有两种选择:

(a)将您自己的类型字段添加到基类
You have a couple of alternatives:

(a) Adding you own type field to the base class
class Animal
{
public:
   int m_type;

   ...
}


那不是很面向对象,将是我的最后选择.

(b)使用C ++的运行时类型信息系统:


That is not very object oriented and would be my last resort.

(b) Use the run-time type information system of C++:

Cat* pCat = dynamic_cast<Cat*> (arr[i]);
if (pCat != NULL)
   pCat->age = 14;


不要忘记运行时类型信息仅适用于多态类,即具有至少一个虚函数的类.在您的情况下,这没问题.实际上,您应该将基类的析构函数设为虚拟,以便可以正确删除数组元素!

在面向对象方面,此替代方法比(a)稍好一些,但对于某些未经适当设计的现有代码,它仍然是最后的选择.

(c)创建一个虚拟函数,该虚拟函数可以执行您想做的任何事情.例如,假设您要通过某种特定于动物类型的公式来调整所有动物的年龄.您可以实现一个虚拟功能,例如:


Don''t forget that run-time type information is only available for polymorphic classes, i.e. classes that have at least one virtual function. That is no problem in your case. In fact, you should make the destructor of your base class virtual, so you can delete your array elements properly!

This alternative is a little better than (a) in terms of object orientation, but still kind of a last resort for some existing code that was not properly designed.

(c) Create a virtual function that does whatever you want to do. For example, say you want to adjust all animal ages by some formula that is animal type specific. You could implement a virtual function like:

class Animal
{
public:
   virtual void AdjustAge () = 0;

...
}

class Cat
{
public:
   virtual void AdjustAge ()
   {
      age = age * CAT_SPECIFIC_FACTOR;
   }
...
}

class Dog
{
public:
   virtual void AdjustAge ()
   {
      age = age * DOG_SPECIFIC_FACTOR + 5;
   }
...
}


然后,在调用代码中,您只需执行以下操作:


Then in the calling code you would just do:

for (i = 0; i < ....)
     arr[i]->AdjustAge();


这将是最面向对象的解决方案.使AdjustAge为抽象虚拟函数(the = 0;)可确保您不要忘记在每个派生类中实现该函数.这种易于维护的方式,对于以后需要维护您代码的人来说很容易解决.


This would be the most object oriented solution. Making AdjustAge an abstract virtual function (the = 0;) makes sure that you don''t forget to implement the function in each derived class. This maintenance friendly and easy to figure out for someone who has to maintain your code later on.


C ++没有任何机制可以在运行时检测类类型.您将需要在类中添加一些额外的属性.另外,有些第三方库可能会有所帮助. Google用于"C ++反射".

多亏了卡洛,我现在知道了正确的答案.
C++ does not have any mechanism for detecting class types at runtime. You would need to add some extra properties to your classes. Alternatively there are some third-party libraries that may help; Google for "C++ reflection".

Thanks to Carlo, I now know the correct answer.