gpt4 book ai didi

c++ - 如何在 C++ 中使用 "interface"

转载 作者:行者123 更新时间:2023-11-30 03:56:45 25 4
gpt4 key购买 nike

我实际上正在做一个项目,它有一个这样的文件。

#include "Preference.h"

#include <string>
#include <list>
#include <exception>

namespace MedicalStudentMatcher
{
class PreferenceException: public std::exception
{
public:
PreferenceException(std::string message) : m_message(message) {}

virtual ~PreferenceException() { }

virtual const char* what() const throw()
{
return m_message.c_str();
}

private:
std::string m_message;

};

class PreferenceReader
{
public:
PreferenceReader(std::string filename);
virtual ~PreferenceReader();

std::list<Preference<std::string, std::string>> ReadPreferences();

private:
std::string m_filename;

std::string trim(std::string str);
};
}


现在的问题是
1.构造函数是如何工作的? (请记住,我是 C++ 中的 STL 以及 C++ 中任何一种高级方法的新手)
2.解释what()函数的语法。(为什么有两个const然后一个char *然后一个throw)
3. 下面一行是什么意思

std::list<Preference<std::string, std::string>> ReadPreferences();

4.我想遍历这个列表。我该怎么做。?

list<Preference<string, string>> hospitalPrefs = hospitalReader.ReadPreferences();
list<Preference<string, string>> studentPrefs = studentReader.ReadPreferences();
list<Match<string, string>> matches;

5.模板类在以下情况下如何工作
以及偏好类如何使用它。什么是 P m_preferrer declare ?在这种情况下,“初始化列表”是如何工作的?

template <class P, class O>
class Preference
{
private:
P m_preferrer;
O m_preferred;
int m_value;

public:
Preference(const P& preferrer, const O& preferred, int value) : m_preferrer(preferrer), m_preferred(preferred), m_value(value) {}
virtual ~Preference() {}

P getPreferrer() const { return m_preferrer; }
O getPreferred() const { return m_preferred; }
int getValue() const { return m_value; }


};

template <class P, class O>
bool less_than(const Preference<P, O>& p1, const Preference<P, O>& p2)
{
return p1.getValue() < p2.getValue();
}
}

即使经过彻底的谷歌搜索,我也找不到这些问题的答案。
请帮忙。如果您需要有关其他文件的更多信息,请发表评论。

最佳答案

  1. PreferenceException 构造函数使用“初始化列表”来设置m_message。既然您知道该术语,就可以搜索它以了解更多信息。
  2. virtual const char* what() const throw() 声明“一个虚拟(运行时多态)函数,它返回一个指向(数组)字符的指针,该指针不能用于修改那些角色。”尾随的“const throw()”表示“此函数无法修改其隐式 this 参数,即它无法修改调用它的类的实例,也无法抛出任何异常。”
  3. 那是一个成员函数声明。该函数应在别处定义。该函数返回一个(双向链接的)首选项列表。
  4. 试试这个:

list<Preference<string, string>> hospitalPrefs = hospitalReader.ReadPreferences();
for (Preference<string, string>& pref : hospitalPrefs)
{
// do something with pref
}

或者,如果您坚持使用 C++98 而不是 C++11:

list<Preference<string, string>> hospitalPrefs = hospitalReader.ReadPreferences();
for (list<Preference<string, string>>::iterator it = hospitalPrefs.begin(); it != hospitalPrefs.end(); ++it)
{
// do something with pref
}

关于c++ - 如何在 C++ 中使用 "interface",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28336432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com