[英]Overloading doesn't work for <<
我有這段代碼,我無法計算出<<操作符的重載:
ostream& operator<<(ostream& out)
{int check=0;
node *temp;
temp=this->head->next;
if(this->head->info==0)
out<<"- ";
while(temp!=NULL)
{ if(temp->info)
{out<<temp->info<<" ";
check=1;
temp=temp->next;}
else if(temp->info==0&&check==1)
{out<<temp->info<<" ";
temp=temp->next;}
else temp=temp->next;
}
return out;
}
我在課堂上有一個結構,並希望輸出大量。 使用鏈接列表創建大量數字。 重載方法在類內部,並且出現錯誤:當我使用運算符<<時不匹配
cout<< B;
內部主要。
有關上述代碼的更多詳細信息。 檢查變量是確保輸出100之類的數字,如00100。如果head-> info == 0數字是負數,如果它是1,數字是正數。 我從head-> next開始,因為第一個節點具有數字符號。
您執行錯誤的方式...類內的重載運算符使您可以將類用作該運算符的左操作數...因此,基本上,您可以執行B << cout;
現在。
您需要在定義您的類的命名空間中將運算符作為函數重載,如下所示:
ostream& operator<<(ostream& out, TYPE_OF_YOUR_CLASS_HERE v)
{
int check=0;
node *temp;
temp=b.head->next;
if(v.head->info==0)
out<<"- ";
while(temp!=NULL)
{
if(v.info) {
out<<v.info<<" ";
check=1;
temp=temp->next;
} else if(temp->info==0&&check==1) {
out<<temp->info<<" ";
temp=temp->next;
}
else
temp=temp->next;
}
return out;
}
正如Alper所建議的,您還需要使operator <<與您的班級成為朋友,以便能夠訪問該班級的私有字段:
class MY_CLASS {
...
friend ostream& operator<< (ostream& out, MY_CLASS v);
};
如果要允許表達式,而類類型恰好在二進制運算符的右側,則最好使用全局operator<<
重載。
std::ostream& operator<<(std::ostream& os, const YourClassType& B)
此外,如果需要訪問私有成員,請使其成為friend
。 否則,只需使其成為非朋友非成員功能即可。
如果要使用標准語法, operator<<
重載不能成為成員函數-您必須將其稱為B << cout
,這遠非理想。
(對於所有二進制運算符, B.operator<<(cout)
表示B
是左側。)
這是我通常要做的。
命名的常規成員函數:
ostream& output(ostream& out) const
{
// Your code here.
}
和一個操作員,它只是調用:
ostream& operator<<(ostream& os, const MyClass& c)
{
return c.output(os);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.