[英]Dealing with operator overload method as a friend
我試圖創建簡單的類並重載其中的一些運算符,但是,我在一開始就失敗了,這是我的代碼:
#include <iostream>
class Person
{
char *firstName;
char *lastName;
int age;
friend std::ostream &operator<<(std::ostream &, const Person &);
public:
Person() : firstName("Piotr"), lastName("Tchaikovsky"), age(10) {}
Person(char* f, char* l, int a)
{
this->firstName = f;
this->lastName = l;
age = a;
}
std::ostream &operator<<(std::ostream& out, const Person &p)
{
out << p.firstName << " " << p.lastName;
return out;
}
};
int main()
{
Person a;
getchar();
getchar();
}
因此,在創建此運算符重載函數之前,我使用調試器來查看構造函數是否可以正常工作,並且它可以正常工作,因為默認值已正確賦給我創建的變量a
,之后,我所做的就是我創建了重載運算符<<
,這是我班上的一個朋友函數,因為被告知由於重載函數的第一個參數的類型,這是一件好事,但是,當我嘗試運行此函數時(注意:我還沒有嘗試打印任何東西,我想先檢查一下一切是否正常),這使我出錯:
“此運算符功能的參數太多”,
“二進制'運算符<<'具有太多參數”和
“'Person :: operator <<':函數聲明中的錯誤;跳過函數體”
但是,我找不到函數聲明的任何問題,而且我可能無法看到對於該函數來說兩個參數可能太多了。 任何幫助表示贊賞!
您將friend
函數聲明為全局非成員函數。 然后定義一個成員函數。
將operator<<
函數的定義移到類之外:
class Person
{
...
friend std::ostream &operator<<(std::ostream &, const Person &);
...
};
std::ostream &operator<<(std::ostream& out, const Person &p)
{
out << p.firstName << " " << p.lastName;
return out;
}
或內聯定義好友函數:
class Person
{
...
friend std::ostream &operator<<(std::ostream &, const Person &)
{
out << p.firstName << " " << p.lastName;
return out;
}
...
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.