c ++ float作为参数传递未正确打印

Koo*_*h56 0 c++

我是c +的新手.我有一个简单的控制台应用程序,header.h其中包含我的课程

class MyClass
{
public:
    float x, y, z;

    MyClass(float x, float y, float z);
};
Run Code Online (Sandbox Code Playgroud)

我有implement.cpp我所有实现的方法,我有

MyClass::MyClass(float x, float y, float z) {};
Run Code Online (Sandbox Code Playgroud)

然后在main.cpp我尝试简单地打印值

int main()
{
  MyClass One(-3.0f, 0.0f, 4.0f);

  cout <<  "Firsth Object: " << One.x << ", " << One.y << ", " << One.z << endl;
}
Run Code Online (Sandbox Code Playgroud)

但在控制台值中打印如下:

-1.07374e + 08,-1.07374e + 08,-1.07374e + 08

我究竟做错了什么?

jpo*_*o38 5

你的构造函数没有初始化任何成员:MyClass::x,MyClass::y也没有MyClass::z.

你必须这样做:

MyClass::MyClass(float x, float y, float z)
{
    this->x = x;
    this->y = y;
    this->z = z;
};
Run Code Online (Sandbox Code Playgroud)

或更好(更惯用,可能更快):

MyClass::MyClass(float x, float y, float z) : 
    x( x ), y( y ), z( z )
{
};
Run Code Online (Sandbox Code Playgroud)

没有它,您将打印MyClass对象的未初始化成员的值One.通常,必须始终初始化类的成员,然后才能使用它们.

  • 转MyClass :: MyClass(float x,float y,float z){}; into MyClass :: MyClass(float x,float y,float z):x(x),y​​(y),z(z){}; (4认同)