简体   繁体   English

C ++多级继承

[英]C++ multilevel inheritance

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 我创建了一个程序,其中有三个类,每个类都相互继承但是当我尝试创建一个派生类函数时,cout给了我一个错误,比如这个

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

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 . std::cout << "Boy2 name is: " << name << std::endl是,好吧......一种std::basic_ostream &你不能把它转换成std::string

This should be OK, just like you wrote getRed() . 这应该没问题,就像你写了getRed()

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

you defined newInf() as a function that returns std::string , 你将newInf()定义为一个返回std :: string的函数,

where you are actually returning std::cout which is ostream . 你实际上在哪里返回std :: cout ,这是ostream

so in run time it tries to convert ostream to string, and fails, that's why you get the message: 所以在运行时它试图将ostream转换为字符串,并失败,这就是你收到消息的原因:

no suitable user-defined conversion from "std::basic_ostream>" to "std::string" exists 没有合适的用户定义的从“std :: basic_ostream>”到“std :: string”的转换

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM