C++ 为什么我的朋友操作重载代码的输出为零
当我试图运行这段代码时,我得到的输出是零,这是不期望的,根据我定义的,我应该得到-1而不是0,我尝试过更改x的值,我尝试过查找垃圾值(如果有)。你们怎么想C++ 为什么我的朋友操作重载代码的输出为零,c++,c++11,C++,C++11,当我试图运行这段代码时,我得到的输出是零,这是不期望的,根据我定义的,我应该得到-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
#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();
}
#包括
使用名称空间std;
nf类{
int x;
公众:
nf(){
x=1;
}
nf(INTA){
a=x;
}
友元nf运算符++(nf n1){
n1.x=-n1.x;
}
无效显示(){
cout
#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();
}
#包括
使用名称空间std;
nf类{
int x;
公众:
nf()
{
x=1;
}
nf(INTA){
x=a;
}
友元nf运算符++(nf&n1)
{
n1.x=-n1.x;
}
无效显示()
{
coutSee提供了重载运算符的正确方法。嗯,我认为键盘上的TAB键似乎已损坏,生成的代码有些不可读,而且很难理解。您可能希望更换键盘,这样您就可以干净、逻辑地缩进代码,使其对其他人可读。只需c绞死alignment@NathanOliver为什么输出是0?同样,看起来a=x;
应该是x=a;
或者更好的是nf(inta):x(a){}
friend nf operator++(nf&n1){n1.x=-n1.x;}
--未定义的行为。应该返回nf
,但不返回任何内容。