gpt4 book ai didi

c++ - 有人建议我这段代码中剩下的内容。运行时未显示任何错误,但输出带有垃圾值

转载 作者:行者123 更新时间:2023-12-02 10:52:55 25 4
gpt4 key购买 nike

运行时未显示任何错误,但输出如下

f1=6.72623e-044
f2=0
f3=6.72623e-044

当我以a = 5初始化时,会出现警告,就像非静态数据成员初始化程序仅可用于-std c plus plus。
然后输出变为
f1 = 5 f2 = 5 f3 = 10
#include<iostream>
#include<cstdio>
using namespace std;
class FLOAT
{
float a;
public:
FLOAT(){}
FLOAT(float x)
{
x=a;
}
FLOAT operator +(FLOAT f);
void display(void);
};
FLOAT FLOAT::operator +(FLOAT f)
{
FLOAT t;
t.a=a+f.a;
return t;
}
void FLOAT::display(void)
{
cout<<a<<endl;
}
int main()
{
FLOAT f1,f2,f3;
f1=FLOAT(3.6);
f2=FLOAT(5.8);
f3=f1+f2;
cout<<"f1="; f1.display();
cout<<"f2="; f2.display();
cout<<"f3="; f3.display();
return 0;
}

最佳答案

这个构造函数没有多大意义,您正在将未初始化的a的值分配给参数x,该参数从不使用:

FLOAT(float x)
{
x = a; //<-- here
}

我想你想要的是:
FLOAT(float x)
{
a = x; //<-- here
}

关于c++ - 有人建议我这段代码中剩下的内容。运行时未显示任何错误,但输出带有垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61736050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com