简体   繁体   English

与朋友一起处理运算符重载方法

[英]Dealing with operator overload method as a friend

I tried to create simple class and to overload some of it's operators, however, i failed at the very beginning, here's my code: 我试图创建简单的类并重载其中的一些运算符,但是,我在一开始就失败了,这是我的代码:

#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();
}

So, before i created this operator overloading function i used debugger to see if constructor is going to work, and it worked, since default values were given correctly to the variable a i created, after that, all i did was that i created function that overloads the operator << and it is a friend function of my class, since i am taught that it is a good thing to do due to the type of the first parameter of overloading function, however, when i try to run this (NOTE: i have not tried to print out anything yet, i wanted to check if everything works fine first) it gives me errors saying: 因此,在创建此运算符重载函数之前,我使用调试器来查看构造函数是否可以正常工作,并且它可以正常工作,因为默认值已正确赋给我创建的变量a ,之后,我所做的就是我创建了重载运算符<< ,这是我班上的一个朋友函数,因为被告知由于重载函数的第一个参数的类型,这是一件好事,但是,当我尝试运行此函数时(注意:我还没有尝试打印任何东西,我想先检查一下一切是否正常),这使我出错:

"too many parameters for this operator function", “此运算符功能的参数太多”,

"binary 'operator <<' has too many parameters" and “二进制'运算符<<'具有太多参数”和

" 'Person::operator<<' :error in function declaration; skipping function body" “'Person :: operator <<':函数声明中的错误;跳过函数体”

however, i can't find any problems with function declaration, and i cannot possibly see how two parameters can be too many for this function. 但是,我找不到函数声明的任何问题,而且我可能无法看到对于该函数来说两个参数可能太多了。 Any help appreciated! 任何帮助表示赞赏!

You declare the friend function as a global non-member function. 您将friend函数声明为全局非成员函数。 Then you define a member function. 然后定义一个成员函数。

Move the definition of the operator<< function to outside the class: 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;
}

Or alternatively define the friend function inline: 内联定义好友函数:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM