首页 > 解决方案 > 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 类型。

标签: c++inheritancederived

解决方案


问题是这个功能:

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));

推荐阅读