0

大师,

给定两个定义如下的类(省略了属性、方法和实现):

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 类的 operator<< 的定义在语法上是正确的。请给任何指示,谢谢。

任汉

  • 平台:赢7
  • MinGW32:版本 2011-11-08
  • GNU Make 3.82
  • G++ 版本 4.6.1

[编辑 1] 我的程序实际上有两个以上的类,并且我的所有类都有 operator<< 重载以进行调试。我对所有类都使用了相同的签名(带有适当的第二个参数)。只有 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);
}
};

用法一:

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];
}
4

1 回答 1

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); };
于 2012-05-02T04:41:04.007 回答