我是c +的新手。我有一个简单的控制台应用程序,header.h
保存我的班级
class MyClass
{
public:
float x, y, z;
MyClass(float x, float y, float z);
};
我有implement.cpp
我所有已实施的方法,我有
MyClass::MyClass(float x, float y, float z) {};
然后在main.cpp
我尝试简单地打印值
int main()
{
MyClass One(-3.0f, 0.0f, 4.0f);
cout << "Firsth Object: " << One.x << ", " << One.y << ", " << One.z << endl;
}
但是在控制台值中打印如下:
-1.07374e + 08,-1.07374e + 08,-1.07374e + 08
我做错了什么?
答案 0 :(得分:5)
您的构造函数未初始化任何成员:> var resolve1, resolve2;
> var promise1 = new Promise(function(r){ resolve1 = r; });
> var thenable = {then:function(r) { console.log(...arguments); resolve2 = r; }};
> resolve1(thenable);
undefined
// you'd expected a call to the then method here
> promise1
Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: Object}
> thenable
Object {}
> resolve2(42)
Uncaught TypeError: resolve2 is not a function(…)
// uh. yeah.
> promise1.then(x => console.log(x))
() { [native code] }, () { [native code] }
// ah there was the call, even with a resolver
Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
> resolve2(42)
42
undefined
> promise1.then(x => console.log(x))
() { [native code] }, () { [native code] }
// but now they fucked up.
// Instead of another call on the thenable, you'd expected the result to be logged
Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
> resolve2(42)
42
// OMG.
undefined
,MyClass::x
或MyClass::y
。
你必须这样做:
MyClass::z
或更好(更惯用,可能更快):
MyClass::MyClass(float x, float y, float z)
{
this->x = x;
this->y = y;
this->z = z;
};
如果没有,您将打印MyClass::MyClass(float x, float y, float z) :
x( x ), y( y ), z( z )
{
};
对象MyClass
的未初始化成员的值。一般情况下,您必须always initialize members of a class才能使用它们。
答案 1 :(得分:2)
你当前的构造函数什么也没做。
您必须初始化对象变量。为此你可以使用
TranslatableRoute::resource('recipe', 'recepten', 'RecipeController');
构造函数中的这种类型的初始化称为初始化列表,您可以读取它here。
这与@ jpo38指出的构造函数具有相同的效果。