【发布时间】:2014-01-05 03:33:09
【问题描述】:
我是 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: binary '
更新版本 1 :
#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;
}
【问题讨论】:
-
你需要为
eMailMsg类型重载operator<<。