c# - C++ 等同于 C# OOP if(Boy b is Student)

标签 c# c++ oop

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

在 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++ 中,多态性仅通过指针 起作用。如果列表负责删除它的元素(通常),那么你应该使用像 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:

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;
}

关于c# - C++ 等同于 C# OOP if(Boy b is Student),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53029074/

相关文章:

c# - WatiN RunScript 在 FireFox 中失败

c++ - 使用 Node.js 作为解释器

c++ - boost 备忘单

c++ - 如果我切换到另一个应用程序,我的MFC应用程序将卡住

javascript - 将原型(prototype)分配给Object.create原型(prototype)有什么区别

javascript - 如何使用面向对象的javascript调用谷歌地图API?

c# - key 存储提供程序不能设置多次(始终使用 Azure Function 进行加密)

c# - 如何为数据绑定(bind)启用属性更改?

c# - 遍历强类型泛型 List<T> 的最佳方法是什么?

javascript - JQuery 绑定(bind)在同一元素上,独特的行为