c++ - C++ 继承“无可行转换”错误
问题描述
有人可以让我知道我做错了什么吗?我正在我的主要对象中创建对象并尝试将字符串变量传递给它的设置器。我不断收到相同的错误“没有可行的转换”
#define PatientType_hpp
#include "PersonType.hpp"
#include "DoctorType.hpp"
#include "dataType.hpp"
class PatientType : public PersonType
{
private:
DoctorType drName;
public:
DoctorType getDrName() const;
void setDrName(DoctorType);
};
#endif /* PatientType_hpp */
//setters and getters
DoctorType PatientType::getDrName() const {
return drName;
}
void PatientType::setDrName(DoctorType drName) {
this->drName = drName;
}
#ifndef DoctorType_hpp
#define DoctorType_hpp
#include "PersonType.hpp"
#include <stdio.h>
class DoctorType: public PersonType
{
private:
string drSpecialty;
public:
string getDrSpecialty()const;
void setDRSpecialty(string);
};
#endif /* DoctorType_hpp */
#include "DoctorType.hpp"
#include <iostream>
string DoctorType::getDrSpecialty()const
{
return drSpecialty;
}
void DoctorType::setDRSpecialty(string drSpecialty)
{
this->drSpecialty=drSpecialty;
}
int main(int argc, const char *argv[]) {
PatientType example;
string drName = "Mr.Scott";
example.setDrName(drName);
// ERROR No viable conversion from 'std::__1::string aka 'basic_string<char, char_traits<char>, allocator<char> >') to 'DoctorType'
}
我期待它能够编译,因为我将一个字符串传递给我认为接受字符串的 Patient 类型。
解决方案
问题是这个功能:
void PatientType::setDrName(DoctorType drName) {
在这里,此函数需要 DoctorType 类型的参数,但您传递的是 std::string。
example.setDrName(drName); // drName is std::string. So, Type mismatch
有很多方法可以解决这个问题:
选项 1:将函数签名更改为void PatientType::setDrName(const std::string &drName) {
选项2:不那么琐碎,但它有效。DoctorType
在接受std::string
作为参数时定义参数化构造函数。
像这样:
DoctorType::DoctorType(const std::string &name): name(name) { }
我认为选项 2 适合您的情况。
正如@t.niese正确建议的那样,您必须显式创建 DoctorType 的对象并将构造函数定义为显式。像这样:
explicit DoctorType::DoctorType(const std::string &name): name(name) { }
并在调用它时:
example.setDrName(DoctorType(drName));
推荐阅读
- mysql - Mysql我可以使用join进行更新吗
- database - 是否有任何 n 元关系的关系分解的一般方法?
- java - JPA 如何创建用于保存的枚举
- c++ - OpenCV CUDA 函数缺失 - 命名空间“cv:cuda”没有成员“resize”
- python - 从特定模式之前的字符串中提取
- react-native - DevTools Profiler 选项卡对于 react-native 应用程序不可见
- javascript - 检查数字是否不在两个值之间
- html - 样式表格式在 Django 项目中不起作用
- python - 根据分隔符获取列表中的值
- node.js - package.json 执行与量角器中的其他构建工具执行有什么不同?