“没有合适的默认构造函数” - 为什么甚至调用默认构造函数?

时间:2013-03-29 19:26:26

标签: c++ constructor member default-constructor

我已经看过其他一些关于此的问题,但我不明白为什么甚至应该在我的情况下调用默认构造函数。我可以提供一个默认的构造函数,但我想了解它为什么这样做以及它会影响它。

error C2512: 'CubeGeometry' : no appropriate default constructor available  

我有一个名为ProxyPiece的类,其成员变量为CubeGeometry。构造函数应该接受CubeGeometry并将其分配给成员变量。这是标题:

#pragma once
#include "CubeGeometry.h"

using namespace std;
class ProxyPiece
{
public:
    ProxyPiece(CubeGeometry& c);
    virtual ~ProxyPiece(void);
private:
    CubeGeometry cube;
};

和来源:

#include "StdAfx.h"
#include "ProxyPiece.h"

ProxyPiece::ProxyPiece(CubeGeometry& c)
{
    cube=c;
}


ProxyPiece::~ProxyPiece(void)
{
}

立方体几何体的标题如下所示。使用默认构造函数对我没有意义。反正我还需要吗?:

#pragma once
#include "Vector.h"
#include "Segment.h"
#include <vector>

using namespace std;

class CubeGeometry
{
public:
    CubeGeometry(Vector3 c, float l);

    virtual ~CubeGeometry(void);

    Segment* getSegments(){
        return segments;
    }

    Vector3* getCorners(){
        return corners;
    }

    float getLength(){
        return length;
    }

    void draw();

    Vector3 convertModelToTextureCoord (Vector3 modCoord) const;

    void setupCornersAndSegments();

private:
    //8 corners
    Vector3 corners[8];

    //and some segments
    Segment segments[12];

    Vector3 center;
    float length;
    float halfLength;
};

2 个答案:

答案 0 :(得分:28)

这里隐式调用默认构造函数:

ProxyPiece::ProxyPiece(CubeGeometry& c)
{
    cube=c;
}

你想要

ProxyPiece::ProxyPiece(CubeGeometry& c)
   :cube(c)
{

}

否则你的ctor相当于

ProxyPiece::ProxyPiece(CubeGeometry& c)
    :cube() //default ctor called here!
{
    cube.operator=(c); //a function call on an already initialized object
}

冒号之后的东西称为member initialization list

顺便说一下,如果我是你,我会将参数改为const CubeGeometry& c而不是CubeGeomety& c

答案 1 :(得分:6)

构造函数开始时会发生成员初始化。如果未在构造函数的成员初始化列表中提供初始值设定项,则该成员将是默认构造的。如果要复制用于初始化成员cube的构造函数,请使用成员初始化列表:

ProxyPiece::ProxyPiece(CubeGeometry& c)
  : cube(c)
{ }

冒号后面的所有内容都是初始化列表。这只是说cube应该使用c进行初始化。

如您所见,cube成员首先默认初始化,然后c 复制分配

相关问题