Frage

I have made a program where there are three classes, each one inherits from one another but when I try to make a derived class function, the cout gives me an error such as this

3   IntelliSense: no suitable user-defined conversion from "std::basic_ostream<char, std::char_traits<char>>" to "std::string" exists   e:\Visual Studio Projects\test\test\Source.cpp  19  10  test

What am I suppose to change and what would be the solution. Also if your could point out my mistake that would be nice

#include<iostream>
#include <string>


std::string name;
class Base{
public:
    void getRed(){
        std::cout << "Your name is : " << name << std::endl;
    }
};

class Boy:public Base{
public:
    Boy(){
        name = "john";
    }
    std::string newInf(){
        return std::cout << "Boy2 name is: " << name << std::endl;
    }
};

class Boy2: public Boy{
public:
    Boy2(){
        name = "Mike";
    }
};

int main(){
    Boy boy;
    boy.getRed();
    Boy2 boy2;
    boy2.newInf();
    system("pause");
    return 0;
}
War es hilfreich?

Lösung

Your compile error is not related to multilevel inheritance.

std::string newInf(){
    return std::cout << "Boy2 name is: " << name << std::endl;
}

This is wrong. std::cout << "Boy2 name is: " << name << std::endl is, well... a kind of std::basic_ostream & and you cannot convert it into std::string.

This should be OK, just like you wrote getRed().

void newInf(){
    std::cout << "Boy2 name is: " << name << std::endl;
}

Andere Tipps

you defined newInf() as a function that returns std::string,

where you are actually returning std::cout which is ostream .

so in run time it tries to convert ostream to string, and fails, that's why you get the message:

no suitable user-defined conversion from "std::basic_ostream>" to "std::string" exists

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top