C++ /(Qt)指向具有特定方法的任何对象

Dar*_*boy 0 c++ qt c++11

如何从其他(TranslationManager)类调用所有类上的特定方法?我简化了很多代码.我只想调用setTranslationTextTranslationManager中的任何类.

这些都要考虑到:

  1. 所有课程都有一个setTranslationText方法
  2. 我们应该使用指向类的指针从TranslationManager调用任何类的setTranslationText

    class Interface
    {
       ...
       public:
         void setTranslationText(QString translatedString); 
    }
    
    class AnyOtherInterface
    {
       ...
       public:
         void setTranslationText(QString translatedString); 
    }
    
    ...
    
    …
    Translationmanager::Translationmanager(){
       AnyClass = Interface; // Pointer to Interface Class
       AnyClass->setTranslatioNText("Text");
    
       AnyClass = AnyOtherInterface; // Pointer to AnyOtherInterface Class
       AnyClass->setTranslatioNText("AnotherText");
    }
    
    
    …
    
    Run Code Online (Sandbox Code Playgroud)

Cor*_*mer 5

你可以使用一个模板

template <typename T>
void setTranslationText(T* t, const QString &translatedString)
{
    t->setTranslationText(translatedString);
}
Run Code Online (Sandbox Code Playgroud)

这样你就不需要一个接口类来继承这个(或多个)方法.然后模板只会编译,如果对于给定的类实例,他们有一个setTranslationText方法定义.你使用它的方式是

Translationmanager::Translationmanager()
{
    setTranslationText(Interface, "Text");                // Pointer to Interface Class    
    setTranslationText(AnyOtherInterface, "AnotherText"); // Pointer to AnyOtherInterface Class
}
Run Code Online (Sandbox Code Playgroud)