C ++继承“无可行转换”错误

问题描述 投票:-2回答:2

有人能让我知道我做错了什么吗?我在我的main中创建对象并尝试将字符串变量传递给它的setter。我一直得到同样的错误“没有可行的转换”

#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++ inheritance derived
2个回答
0
投票

问题在于:

void PatientType::setDrName(DoctorType drName)

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

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

修复是显而易见的:要么修改原型,要么接受string参数,或者在调用方法时,给它一个DoctorType参数。


0
投票

问题是这个功能:

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));
© www.soinside.com 2019 - 2024. All rights reserved.