C++多级继承

标签 c++ class inheritance multiple-inheritance

我编写了一个程序,其中包含三个类,每个类都相互继承,但是当我尝试创建派生类函数时,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

我应该改变什么,解决方案是什么。另外,如果您能指出我的错误,那就太好了

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

最佳答案

你的编译错误与多级继承无关。

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

这是错误的。 std::cout << "Boy2 name is: " << name << std::endl是,好吧……一种std::basic_ostream &你不能把它转换成 std::string .

这应该没问题,就像你写的一样getRed() .

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

关于C++多级继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21635813/

相关文章:

c++ - ={} 和 {} 风格的初始化在 C++11 中是否相同?

Python:我应该在这里使用委托(delegate)还是继承?

c++ - 返回一个本地指针

c++ - 删除指向 unordered_map 中对象的指针

java - 如何在Java中对 "either or"类的返回类型进行建模?

javascript - 自定义类的服务器端 onchange 事件

java - 父类是否应该引用子类?

inheritance - 如何在Grails/GORM中将域类模型对象从一个派生类更改为另一个

c++ - OpenGL - 渲染到纹理中

c# - 不能在不同的命名空间中使用我的新字段