【问题标题】:Return a function from multiple derived classes从多个派生类返回一个函数
【发布时间】:2012-11-12 11:37:32
【问题描述】:

我有一个基类和多个派生类。每个派生类都有一个构造函数,它接受在基类中初始化的参数。所有的构造函数都是不同的,但是它们都接受一个公共参数,我们称之为Name

有没有办法让我以比一个接一个地调用它们更短的方式显示每个派生类的名称?

这是一个例子。假设我的基类是Father,派生类是Brother, Sister, HalfBrother, HalfSister,这是我的驱动程序文件:

cout << Brother::Brother().getName() << endl
     << Sister::Sister().getNAme() << endl
     << HalfBrother::HalfBrother().getNAme() << endl
     << HalfSister::HalfSister().getName() << endl;

这会很好地返回它们,但是有没有更简单的方法可以做到这一点,以便我可以从所有派生类中获取所有名称,而不必一个一个地编写它们?

【问题讨论】:

  • 我不认为我们可以这样做,但如果我们使用 super() 或类似的东西,那么它可能是可能的。我正在等待您的问题的答复(答案)。
  • 你为什么要构造临时对象来打印它们的名称,这个通用参数名称在哪里 - 我看到它们没有带任何参数?
  • 为什么不在Father 中创建getName() 方法?通过这样做,您只是遍历您的父亲引用/指针列表并调用father-&gt;getName()
  • 这些名称是特定于类还是特定于您创建的各个对象?

标签: c++ inheritance multiple-inheritance


【解决方案1】:

您可以创建类的静态注册表,并从您插入到要注册的类中的静态成员的构造函数中填充它。

在标题中:

class Registration {
    static vector<string> registered;
public:
    static void showRegistered() {
        for (int i = 0 ; i != registered.size() ; i++) {
            cout << registered[i] << endl;
        }
    }
    Registration(string name) {
        registered.push_back(name);
    }
};

在 CPP 文件中:

vector<string> Registration::registered;

有了这个类,你可以这样做:

在标题中:

class A {
    static Registration _registration;
};

class B {
    static Registration _registration;    
};

class C {
    static Registration _registration;    
};

在 CPP 文件中:

Registration A::_registration("quick");
Registration B::_registration("brown");
Registration C::_registration("fox");

最后一部分是关键:静态 _registration 变量的声明有一个副作用 - 它们将名称插入到 Registration 类的 vector&lt;string&gt; registered 中,没有特定的顺序。您现在可以检索名称、打印出来,或对它们做任何您想做的事情。我添加了一个用于打印的成员函数,但显然你不受它的限制。

这是demo on ideone - 它会打印出来

quick
brown
fox

【讨论】:

    【解决方案2】:

    老实说,我不确定我是否理解您的问题。正如评论中所说,你应该让 getName() 成为父亲中的一个方法。

    class Father {
    public:
    
        Father(string name) : m_name(name) {
        }
    
        string& getName() {
            return m_name;
        }
    
    private:
        string m_name;
    };
    
    class Brother : public Father {
    public:
        Brother(string name) : Father(name) {
        }
    };
    
    class Sister : public Father {
    public:
        Sister(string name) : Father(name) {
        }
    };
    

    所以你可以有类似的东西:

    vector<Father *> fathers;
    Brother brother("...");
    Sister sister("....");
    
    father.push_back(&brother);
    father.push_back(&sister);
    
    for (vector<Father*>::iterator itr = fathers.begin();
            itr != fathers.end();
            ++itr) {
        cout << (*itr)->getName() <<endl;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-04
      • 2015-06-21
      • 1970-01-01
      • 2016-08-03
      • 2017-11-23
      相关资源
      最近更新 更多