C++继承"No Viable Conversion"错误

C++ Inheritance "No Viable Conversion" Error

本文关键字:Conversion 错误 Viable No 继承 C++      更新时间:2023-10-16

有人可以让我知道我在做什么错吗?我将对象制作在我的主体中,并试图将字符串变量传递给其设置器。我一直遇到相同的错误"无可行的转换"

#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'
}

我希望它会编译,因为我将字符串传递到我认为接受字符串的患者类型中。

问题在这里:

void PatientType::setDrName(DoctorType drName)

在这里,您希望发送DoctorType参数。但是,在打电话给您使用时:

example.setDrName(drName);其中drNamestring,而不是DoctorType参数。

修复程序很明显:要么修改原型,因此它接受string参数,或者在调用该方法时,给它一个DoctorType参数。

问题是此功能:

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正确建议的那样,您必须明确创建医生的对象,并将构造函数定义为明确的。这样:

explicit DoctorType::DoctorType(const std::string &name): name(name) { }

在调用它时:

example.setDrName(DoctorType(drName));
相关文章: