猪猪虾 发表于 2021-11-10 21:36:49

c++ 成员函数重载



问题:这里定义了新的一个类对象,来接受对象P1和P2的和,Person p3 = p1 + p2;
这个语句Person p3 = p1 + p2;是怎么实现 调用Person operator+(Person& p),这个调用过程是怎样的?能详细指教一下吗
成员函数的传入对象是一个,却能实现两个成员函数的相加

//加号运算符重载
#include <stdio.h>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
using namespace std;
class Person
{
public:

        //1.成员函数重载 +
        Person operator+(Person& p)
        {
                Person temp;
                temp.m_a = this->m_a + p.m_a;
                temp.m_b = this->m_b + p.m_b;
                return temp;
        }
        int m_a;
        int m_b;
};

void test()
{
        Person p1;
        p1.m_a = 10;
        p1.m_b = 20;
        Person p2;
        p2.m_a = 20;
        p2.m_b = 30;

        Person p3 = p1 + p2;

        cout << "p3.m_a = " << p3.m_a << endl;
        cout << "p3.m_b = " << p3.m_b << endl;
}
int main()
{
        test();
        return 0;
}

人造人 发表于 2021-11-10 21:52:39

这个语句Person p3 = p1 + p2;是怎么实现 调用Person operator+(Person& p)
想知道怎么实现的,去看汇编语言

人造人 发表于 2021-11-10 22:00:06

        movl        $10, -32(%rbp)
        movl        $20, -28(%rbp)
        movl        $20, -24(%rbp)
        movl        $30, -20(%rbp)
        leaq        -24(%rbp), %rdx
        leaq        -32(%rbp), %rax
        movq        %rdx, %rsi
        movq        %rax, %rdi
        call        Person::operator+(Person&)
        movq        %rax, -16(%rbp)

人造人 发表于 2021-11-10 22:02:10

就是这样实现调用的

人造人 发表于 2021-11-10 22:05:05

传给 Person::operator+(Person&) 这个函数的参数有 2 个
第 0 个是变量 p1 的地址
第 1 个是变量 p2 的地址

lhgzbxhz 发表于 2021-11-13 19:32:29

p1 + p2
//相当于
p1.operator+(p2)
//你可以自己试试
页: [1]
查看完整版本: c++ 成员函数重载