Is it possible to create an object of a class, inside a class definition, without using default constructor?
class Vector3D {
public:
Vector3D(int x, int y, int z);
virtual ~Vector3D();
private:
int m开发者_运维百科_X;
int m_y;
int m_z;
};
class CustomClass {
private:
Vector3D m_Vec(50,50,50); //error
};
Yes, this can be done, but the syntax is different:
class Vector3D {
public:
Vector3D(int x, int y, int z);
virtual ~Vector3D();
private:
int m_X;
int m_y;
int m_z;
};
class CustomClass {
private:
Vector3D m_Vec;
public:
CustomClass(): m_Vec(50,50,50) {}
};
class CustomClass {
private:
Vector3D m_Vec;
public:
CustomClass() : m_Vec(50,50,50) {}
}
In the (now current) C++11 standard you can actually do that using uniform-initialization and Non-static data member initializers (N2756):
class CustomClass {
private:
Vector3D m_Vec{50,50,50};
};
Now, the problem is that not all compilers have support for all of the new features. In particular gcc 4.7 is the first of the gcc versions to support this form of initialization.
精彩评论