給出定義如下兩個類(屬性,方法和實施省略):
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行給出了我的很好的彙編,這意味着我對B類的運算符< <的定義在語法上是正確的。請給任何指示和感謝。
蔭漢
- 平臺:Win 7
- MINGW32:版本2011-11-08
- GNU請3.82
- G ++版本4.6.1
[編輯1 ] 我的程序實際上有兩個以上的班級,而我所有的班級都有操作員< <過載進行調試。我對所有類都使用了相同的簽名(適當的第二個參數)。只有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);
}
};
用法答:
3210用法B(這是錯誤):
CPeople *people_total = new CPeople[cntTotalPop];
for (pIdx = 0; pIdx < cntTotalPop; pIdx++)
{
std::cout << people_total[pIdx];
}
你的'operator <<'(for B)實現的函數頭是什麼樣的? – chris
你有沒有在課堂結束時錯過了';'?你也可以發佈一些相關的代碼出現在第3行。 – iammilind
實際上所有運算符<<都被定義爲朋友,並且它們在類定義中實現 –