[英]No operator << matches these operands
我一直在这里阅读一两个小时的问题关于我得到的这个错误,他们中的大多数都忘了#include string(我已经做过),或者重载<<运算符。
这是有问题的代码:
void Student::getCoursesEnrolled(const vector<Course>& c)
{
for (int i = 0; i < c.size(); i++)
{
cout << c[i] << endl;
}
}
而我得到的错误:
Error: No operator matches these operands
operand types are: std::ostream << const Course
我要做的就是返回矢量。 我读过关于重载<<运算符但是我们没有在课堂上学到任何这些,所以我假设有另一种方法可以做到这一点?
我感谢你的时间!
我要做的就是返回矢量。
不完全的; 你正试图用cout
打印它。 并且cout
不知道如何打印Course
对象,除非你提供一个重载的operator<<
告诉它如何这样做:
std::ostream& operator<<(std::ostream& out, const Course& course)
{
out << course.getName(); // for example
return out;
}
有关详细信息,请参阅StackOverflow上的运算符重载圣经 。
流操作符<<
用于“输出”该对象的某些表示。 如果你不想重载运算符,只需选择一些属性来输出:
for (int i = 0; i < c.size(); i++)
{
cout << c[i].Name << endl; // assuming Name is a property of Course
}
当您重载操作员时,您只需决定Course
的正确表示:
ostream& operator<< (ostream &out, Course &c)
{
out << c.Name "(" << c.Description << ")";
return out;
}
您的Course
类需要实现一个操作符:
class Course
{
public:
/*
* Your code here
*/
// Probably missing this:
friend std::ostream& operator << (std::ostream& os, const Course& course)
{
os << course.name(); // etc..
return os;
};
}; // eo class Course
由于您尚未学习重载operator<<
,因此您可以执行的操作是打印Course
类的每个成员。 你还没有发布Course
的定义,但也许是这样的:
class Course
{
public:
int get_number() { return _number; }
const std::string& get_name() { return _name; }
private:
int _number;
std::string _name;
};
然后你可以说:
void Student::getCoursesEnrolled(const vector<Course>& c)
{
for (int i = 0; i < c.size(); i++)
{
cout << c[i].get_number() << " "
<< c[i].get_name() << std::endl;
}
}
问题是operator <<不会重载您尝试在语句中输出的类型的Course
对象
cout << c[i] << endl;
您需要重载此运算符或编写自己的函数,该函数将在std::ostream
输出类型为Course
的对象
例如,假设下面是类Course
的定义
class Course
{
private:
std::string name;
unsigned int duration;
public:
Course() : duration( 0 ) {}
Course( const std::string &s, unsigned int n ) : name( s ), duration( n ) {}
std::ostream & out( std::ostream &os ) const
{
return ( os << "Course name = " << name << ", course duration = " << duration );
}
};
什么时候可以写
std::vector<Course> v = { { "A", 1 }, { "B", 2 }, { "C", 3 } };
for ( const Course &c : v ) c.out( std::cout ) << std::endl;
相反,成员函数可以重载operator <<。 例如
class Course
{
private:
std::string name;
unsigned int duration;
public:
Course() : duration( 0 ) {}
Course( const std::string &s, unsigned int n ) : name( s ), duration( n ) {}
friend std::ostream & operator <<( std::ostream &os, const Course & c )
{
return ( os << "Course name = " << c.name << ", course duration = " << c.duration );
}
};
并用它作为
std::vector<Course> v = { { "A", 1 }, { "B", 2 }, { "C", 3 } };
for ( const Course &c : v ) std::cout << c << std::endl;
你的问题是这个特殊的部分:
cout << c[i]
在你的情况下, c[i]
是一个类型为Course
的对象,正如dvnrrs正确指出的那样。 所以要么:
Course
对象在某种程度上是一个原始的typedef
尝试显式地将它转换为字符串类型(或类似)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.