开发者

Is it possible to create an object of a class, inside a class definition, without using default constructor

开发者 https://www.devze.com 2023-04-10 06:19 出处:网络
Is it possible to create an object of a class, inside a class definition, without using default constructor?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号