问题描述
报错:
error: no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘void’)
std::shared_ptr<Cat> get_shared_ptr() { std::shared_ptr<Cat> cat_p = std::make_shared<Cat>("local cat"); return cat_p; } int main(int argc, char *argv[]) { cout<<"----3----"<<endl; std::shared_ptr<Cat> c_p = get_shared_ptr(); c_p->cat_info(); //cout<<c_p->cat_info()<<endl; //错误地方 cout<<c_p->get_name()<<endl; cout<<"------yz------"<<endl; return 0; }
cat.h
#ifndef CAT_H #define CAT_H #include <string> #include <iostream> class Cat { public: Cat(std::string name); Cat() = default; ~Cat(); void cat_info() const { std::cout<<"cat info name : "<<name << std::endl; } std::string get_name() const { return name; } void set_cat_name(const std::string &name) { this->name=name; } private: std::string name{"Mimi"}; }; #endif
cat.cpp
# include "/home/CLearn02/demo02/include/cat.h" Cat::Cat(std::string name) : name(name) { std::cout<<"Constructor of Cat :"<< name <<std::endl; } Cat::~Cat() { std::cout<<"Destructor of Cat:"<<name<<std::endl; }
原因分析:
因为在类Cat中,cat_info()的返回值是void,"<<"不能接收void类型的返回值,所以cout<<c_p->cat_info()<<endl这条语句错误
直接用c_p->cat_info()输出即可;