C ++ Наследование Ошибка «Нет жизнеспособного преобразования» - PullRequest
0 голосов
/ 17 февраля 2019

Может кто-нибудь сообщить мне, что я делаю не так?Я делаю объект в моем main и пытаюсь передать строковую переменную его установщику.Я продолжаю получать ту же ошибку "Нет жизнеспособного преобразования"

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

I 'Я ожидаю, что он скомпилируется, потому что я передаю строку в тип Patient, который, я думаю, принимает строки.

Ответы [ 2 ]

0 голосов
/ 17 февраля 2019

Проблема заключается в следующей функции:

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));
0 голосов
/ 17 февраля 2019

Проблема заключается в следующем:

void PatientType::setDrName(DoctorType drName)

Здесь вы ожидаете отправить параметр DoctorType.Однако при вызове вы используете:

example.setDrName(drName);, где drName - это string, а не DoctorType параметр.

Исправление очевидно: либо измените прототип так, чтобы он принимал параметр string, либо, при вызове метода, присвойте ему параметр DoctorType.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...