c# - 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++
多态中只能通过指针起作用。如果列表负责删除其元素(通常),那么您应该使用类似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;
}
推荐阅读
- facebook - Facebook Grap Api 获取视频图片不适用于某些视频
- c++ - 连接字符串的 C++ 最佳实践
- javascript - 使用 Javascript 读取 XML 文件
- java - 从 Int 数组中查找并删除对
- ruby-on-rails - 如何从请求字符串加载控制器方法,如“controller#action”
- python - 尝试将 PNG 图像添加到 tkinter 窗口时出现图像未识别错误
- r - R中的过滤器列表
- javascript - 如何从单个构建中加载单独的组件
- java - 使用 java.util.List.sort 和 java.time.LocalDateTime compareTo 方法
- python - 无法升级 awscli:没有名为 _internal 的模块和其他错误