首页 > 解决方案 > C++ 等价于 C# OOP if(Boy b is Student)

问题描述

我正在尝试使用 C++ 实现上述系统。以前,我使用 C# 和 OOP 来编写程序,所以这将是我第一次使用 C++,我知道这两种语言之间存在一些差异。我想要做的是我想计算日志类成员列表中的选民人数。

在 C# 中,我将使用

foreach(Member m in _members) {
    if(Member m is Voter) {
        votercount++;
    }
}

但是,我不确定在 cpp 中,这个工具是否正确?在我的 Logbook.h 文件中

class Logbook
{
private:
    std::list<Member> _members;

在我的 Logbook.cpp 文件中:

int Logbook::CandidateCount() {
  int membercount;
  for(Member m: _members) {
    if (Member* m=dynamic_cast<const Member*>(&Candidate)) membercount++;
  }
  return membercount;
}

&Candidate它在显示标识符 Candidate 未定义的位置显示错误。是因为 Logbook 类无法到达 Candidate 类吗?

非常感谢任何回复和帮助。

标签: c#c++oop

解决方案


您在这里做错了几件事。首先,您没有初始化计数变量,因此它将使用一些随机值开始(它可能为零或其他值)。

接下来,您需要存储指向列表成员的指针,因为在C++多态中只能通过指针起作用。如果列表负责删除其元素(通常),那么您应该使用类似std::unique_ptr的智能指针:

class Logbook {
public:
    int CandidateCount();

    // virtual destructor is (usually) important for polymorphic types
    virtual ~Logbook() = default;

    // store pointers in your list    
    std::list<std::unique_ptr<class Member>> members;
};

然后,您可以遍历该列表,尝试将每个指针动态转换为您要计数的类型。如果它返回一个有效的指针,那么你就知道它属于那种类型。否则nullptr将返回 a:

class Member: public Logbook {};
class Candidate: public Member {};
class Voter: public Member {};

int Logbook::CandidateCount()
{
    int membercount = 0; // initialize this!!!!

    for(auto& m : members) { // use reference here to avoid making a copy

        if(dynamic_cast<Candidate*>(m.get()))
            membercount++;
    }

    return membercount;
}

注意:如果你想做的不仅仅是计算你的候选人,你可以保持从动态转换中获得的指针,如下所示:

class Candidate: public Member { public: void do_something(){} };

int Logbook::CandidateCount()
{
    int membercount = 0; // initialize this!!!!

    for(auto& m : members) { // use reference here to avoid making a copy

        if(auto c = dynamic_cast<Candidate*>(m.get())) {
            membercount++;

            // c is not nullptr and is type Candidate*    
            c->do_something(); // use your Candidate like this
        }
    }

    return membercount;
}

推荐阅读