c++ - 在 C++ 的单独头文件中完成函数体?
问题描述
我有一个家庭作业任务,我应该完成位于单独文件中的函数主体,该文件Find.h
应该以下面编写的代码应该成功编译的方式完成:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include "Find.h"
using namespace std;
class Company {
std::string name;
int id;
public:
std::string getName() const {
return this->name;
}
int getId() const {
return this->id;
}
friend std::istream& operator>>(std::istream& stream, Company& company);
};
std::istream& operator>>(std::istream& stream, Company& company) {
return stream >> company.name >> company.id;
}
std::ostream& operator<<(std::ostream& stream, const Company& company) {
return stream << company.getName() << " " << company.getId();
}
int main() {
using namespace std;
vector<Company*> companies;
string line;
while (getline(cin, line) && line != "end") {
istringstream lineIn(line);
Company* c = new Company();
lineIn >> *c;
companies.push_back(c);
}
string searchIdLine;
getline(cin, searchIdLine);
int searchId = stoi(searchIdLine);
Company* companyWithSearchedId = find(companies, searchId);
if (companyWithSearchedId != nullptr) {
cout << *companyWithSearchedId << endl;
}
else {
cout << "[not found]" << endl;
}
for (auto companyPtr : companies) {
delete companyPtr;
}
return 0;
}
这是我完成Find.h
文件的不完整尝试(程序应输出与给定 id 匹配的公司的 id 和名称):
#ifndef FIND_H
#define FIND_H
#include "Company.h"
#include <vector>
using namespace std;
Company* find(vector<Company*> vc, int id) {
for (int i = 0; i < vc.size(); i++) {
if (vc[i]->getId() == id) {
//I do not know what to write here as to return a pointer
//to the required element so as to fulfil the requirement?
}
}
return nullptr;
}
#endif // !FIND_H
解决方案
对于 .h 文件 for 循环中的特定问题,请尝试:
return vc[i]; //vc is a vector of Company pointers, this returns the pointer at vc index i
对于输出部分,请考虑:
cout << companyWithSearchedId->getId() << " " << companyWithSearchId->getName() << endl;
总的来说,这里还有更多问题,花点时间解决它。
推荐阅读
- json - scala - 使用 json4s 分解时如何更改字段名称?
- python - Python 为什么在这段代码中使用 open(filename) 两次?
- python - Virtualenv 未在 Windows 10 PowerShell 中激活
- spring - 保存对象时未填充 Spring Boot JPA@CreatedDate @LastModifiedDate
- r - c() 和 | 之间的区别 在使用 R 的子集中
- javascript - 将字符串转换为对象键值
- firebase - 什么用例有 FirebaseUser 的 reload() 功能?
- java - 如何创建能够支持 @JsonFilter 注释 POJO 的全局过滤器
- laravel - Laravel Dusk:http POST 引发的 Curl 错误
- go - GoLang 将 STDOUT 和 STDERR 写入 log15 文件