师,
给定两个类定义如下(省略属性,方法和实现):
struct A { friend std::ostream& operator << (std::ostream& o, const A& c); };
struct B { friend std::ostream& operator << (std::ostream& o, const B& c); };
我使用了以下课程:
ln 1: A *arrayA = new A[10];
ln 2: B *arrayB = new B[10];
ln 3: /* some codes to initialize arrayA and arrayB */
ln 4: for (int i = 0; i < 10; i++) { std::cout << arrayA[i]; } // this work
ln 5: for (int j = 0; j < 10; j++) { std::cout << arrayB[j]; } // this complain
我的编译器抱怨B类为
error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue
to 'std::basic_ostream<char>&&'
../lib/gcc/mingw32/4.6.1/include/c++/ostream:581:5 error initializing argument 1
of 'std::basic_ostream<_CharT, _Traits>&
std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&)
[with _CharT = char, _Traits = std::char_traits<char>, _Tp = ClsB]
我不知道第5行有什么问题。评论主程序的第5行给出了我的良好编译,这意味着我对运算符的定义&lt;&lt;因为B类在语法上是正确的。请给出任何指示并表示感谢。
Yam Hon[编辑1] 我的程序实际上有两个以上的类,我的所有类都有运算符&lt;&lt;重载以进行调试。我为所有类使用了相同的签名(带有适当的第二个参数)。只有B级才会出现此错误。
[编辑2] 完整版的课程:
struct CPeople { // this is class B
int age;
int ageGroup;
int zipcode;
int communityID;
int areaID;
int familyID;
int contactID;
int contactType; /* P, D, E, M, H, W */
int state;
int vaccinated; /* 0 = unvac, 1 = vaccinated */
friend std::ostream& operator<< (std::ostream& o, const CPeople& c)
{
o << "CPeople (" << static_cast<void const *>(&c) << "): "
<< "\tAge Group: " << c.ageGroup
<< "\tZip Code: " << c.zipcode
<< "\tCommunityID: " << c.communityID
<< "\tArea ID: " << c.areaID
<< "\tFamily ID: " << c.familyID
<< "\tSchool Type: " << c.contactType
<< "\tContact ID: " << c.contactID
<< "\tState: " << c.state
<< "\tVaccination: " << c.vaccinated;
return (o << std::endl);
}
};
struct CWorkGroup : public CContact { // this is class A
/* to which community this member belongs */
std::vector<long> member_com;
CStatistics statistics;
friend std::ostream& operator<< (std::ostream& o, const CWorkGroup& c)
{
o << "CWorkGroup (" << static_cast<void const *>(&c) << "): ";
o << "avflag = " << c.avflag << "; member: " << c.size();
for (int i = 0; i < c.size(); i++)
{
o << "; (" << i << " = " << c.member[i] << ")";
}
o << std::endl;
return (o << c.statistics);
}
};
用法A:
for (int i = 0; i < cntWG; i++) { std::clog << WG[i]; } std::clog << std::endl;
用法B(这是错误):
CPeople *people_total = new CPeople[cntTotalPop];
for (pIdx = 0; pIdx < cntTotalPop; pIdx++)
{
std::cout << people_total[pIdx];
}
答案 0 :(得分:1)
类和结构需要以分号结束,因此在两行的末尾添加分号:
struct A { friend std::ostream& operator << (std::ostream& o, const A& c); };
struct B { friend std::ostream& operator << (std::ostream& o, const B& c); };