为什么我的朋友操作超载代码将输出算出为零

Why is the output is coming out to be zero for my friend operation overloaded code

本文关键字:输出 我的朋友 操作 超载 代码 为什么      更新时间:2023-10-16

当我试图运行此代码时,我将输出视为零,这不是我所定义的,我应该得到-1而不是0,我尝试更改X的值,如果有的话,我尝试查找垃圾值。你们想什么?

#include<iostream>
using namespace std;
class nf {
    int x;
public:
    nf() {
        x=1;
    }
    nf(int a) {
        a=x;
    }
    friend nf operator ++(nf n1) {
        n1.x=-n1.x;
    }
    void display() {
        cout<<x;
    }
};
int main()
{
    nf obj(1),obj2;
    obj2=++obj;
    obj2.display();
}

排序。

#include<iostream>
using namespace std;
class nf{
    int x;
    public:
    nf()
    {
        x=1;
    }
    nf(int a){
        x=a;
    }
friend nf operator ++(nf &n1)
{
    n1.x=-n1.x;
}
void display()
{
    cout<<x;
}

};
int main()
{
 nf c1;
 ++c1;
 c1.display();
}