我是一名c ++初学者。有人能告诉我如何打印名为mailVector的矢量。这是我的代码:
#include<iostream>
#include<vector>
using namespace std;
struct eMailMsg {
string to; // i.e. "professor@stanford.edu"
string from; // i.e. "student@stanford.edu"
string message; // body of message
string subject; // i.e. "CS106 Rocks!"
int date; // date email was sent
int time; // time email was sent
};
int main(){
vector <eMailMsg> mailVector;
eMailMsg professor={"professor@stanford.edu","student@stanford.edu","body of message","CS106 Rocks",4,16};
mailVector.push_back(professor);
for( std::vector<eMailMsg>::const_iterator i = mailVector.begin(); i != mailVector.end(); ++i)
std::cout << *i << ' ';
return 0;
}
相应的错误是错误1错误C2679:二进制'&lt;&lt;' :找不到哪个运算符采用'const eMailMsg'类型的右手操作数(或者没有可接受的转换)
更新了ver1 :
#include<iostream>
#include<vector>
#include<iterator>
using namespace std;
struct eMailMsg {
string to; // i.e. "professor@stanford.edu"
string from; // i.e. "student@stanford.edu"
string message; // body of message
string subject; // i.e. "CS106 Rocks!"
int date; // date email was sent
int time; // time email was sent
};
ostream& operator<<(ostream& os, const eMailMsg& rightOp)
{
os << rightOp.to << " " << rightOp.from << "etc ...";//error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const std::string' (or there is no acceptable conversion)
return os;
// We're writing std::string here and C++ can do that
}
int main(){
vector <eMailMsg> mailVector;
eMailMsg professor={"professor@stanford.edu","student@stanford.edu","body of message","CS106 Rocks",4,16};
mailVector.push_back(professor);
for( std::vector<eMailMsg>::const_iterator i = mailVector.begin(); i != mailVector.end(); ++i)
std::cout << *i << ' ';
return 0;
}
答案 0 :(得分:3)
您正在尝试打印eMailMsg
类型。 C ++不知道如何做到这一点,你需要告诉它。
重载ostream& operator<<(ostream& os, const eMailMsg& rightOp)
以便教它。
您可以执行以下操作:
... {
os << rightOp.to << " " << rightOp.from << "etc ...";
return os;
// We're writing std::string here and C++ can do that
}
答案 1 :(得分:1)
试试这个:
#include<iostream>
#include<vector>
using namespace std;
struct eMailMsg {
string to; // i.e. "professor@stanford.edu"
string from; // i.e. "student@stanford.edu"
string message; // body of message
string subject; // i.e. "CS106 Rocks!"
int date; // date email was sent
int time; // time email was sent
operator char const * () const
{
return to.c_str();
}
};
int main(){
vector <eMailMsg> mailVector;
eMailMsg professor={"professor@stanford.edu","student@stanford.edu","body of message","CS106 Rocks",4,16};
mailVector.push_back(professor);
for( std::vector<eMailMsg>::const_iterator i = mailVector.begin(); i != mailVector.end(); ++i)
std::cout << *i << ' ';
return 0;
}
请注意,转换运算符方法格式化结构,并且c ++编译器决定使用该运算符转换为“char *”,因为它是“&lt;&lt;”的有效参数类型流出的运营商。