![](/img/trans.png)
[英]error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘void’)
[英]\main.cpp|103|error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'Person')
這是我的第一個問題,所以請忍受我犯的任何格式錯誤,我將嘗試對其進行編輯:)
我有這個函數,它找到某個數據類型X的三個變量的最大值並返回它。
template <class X>
X fmax(X a, X b, X c)
{
X temp=a;
if (b>temp)
temp=b;
if(c>temp)
temp=c;
return temp;
}
然后是班級人,看起來像這樣
class Person
{
private:
char* name;
int height;
char gender;
public:
Person(){}
Person(char * name,int height, char gender)
{
int sz=strlen(name);
this->name= new char [sz];
strcpy(this->name,name);
this->height=height;
this->gender=gender;
}
void setName(char* name)
{
int sz=strlen(name);
this->name= new char [sz];
strcpy(this->name,name);
}
void setHeight(int h){this->height=h;}
void setGender(char g){this->gender=g;}
char* getName(){return this->name;}
int getHeight(){return this->height;}
char getGender(){return this->gender;}
Person operator= (Person p)
{
int sz=strlen(p.getName());
this->name= new char [sz];
strcpy(this->name,p.getName());
this->height=p.getHeight();
this->gender=p.getGender();
return *this;
}
bool operator> (Person p)
{
if(this->getHeight()>p.getHeight())//The persons should be compared using their heights.
return true;
return false;
}
};
而且我也重載了ostream:
ostream &operator<<(ostream &mystream, Person &p)
{
mystream<<"The person's name is: "<<p.getName()<<endl;
mystream<<"The person's height is: "<<p.getHeight()<<endl;
mystream<<"The person's gender is: "<<p.getGender()<<endl;
return mystream;
}
但是我的主要錯誤:
int main()
{
Person a("Zacky",178,'m');
Person b("Jimmy",199,'m');
Person c("Matt",200,'m');
Person d=fmax(a,b,c);
cout<<d<<endl;
cout<<fmax(a,b,c);<<endl;//the error strikes here.
return 0;
}
顯然,我可以使用fmax函數初始化對象d后退出它,但不能直接退出該函數返回的內容。 關於我需要解決的任何想法?
PS我很抱歉,如果以前曾問過這個問題,我搜索了該網站,卻沒有找到類似的東西:/
您需要更改以下內容:
由於fmax()
返回不可更改的右值,因此您應該使用
ostream &operator<<(ostream &mystream, const Person &p);
// ^^^^^
作為輸出運算符重載的簽名(我通常建議這樣做)。
進而需要使您的getter函數成為const
成員函數:
class Person
{
// ...
const char* getName() const {return this->name;}
int getHeight() const {return this->height;}
char getGender() const {return this->gender;}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.