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

AAB*_*AAB 13 c++ constructor member default-constructor

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

error C2512: 'CubeGeometry' : no appropriate default constructor available  
Run Code Online (Sandbox Code Playgroud)

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

#pragma once
#include "CubeGeometry.h"

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

和来源:

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

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


ProxyPiece::~ProxyPiece(void)
{
}
Run Code Online (Sandbox Code Playgroud)

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

#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;
};
Run Code Online (Sandbox Code Playgroud)

Arm*_*yan 29

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

ProxyPiece::ProxyPiece(CubeGeometry& c)
{
    cube=c;
}
Run Code Online (Sandbox Code Playgroud)

你要

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

}
Run Code Online (Sandbox Code Playgroud)

否则你的ctor等同于

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

冒号后面的东西称为成员初始化列表.

顺便说一句,我想借此参数作为const CubeGeometry& c代替CubeGeomety& c,如果我是你.

  • 为了更清楚,也许你可以在你的"相同"片段中将`cube = c;`改为`cube.operator =(c);`.这将有助于解释赋值不会(从语言角度)重新初始化`cube`. (3认同)
  • @AABoucher:是的.虽然不是*之前的*构造函数,而是在它的开头.Ctor-init-list是构造函数调用的一部分.但是,是的,一旦你输入了构造函数的*body*,所有成员都被初始化 - 显式地在ctor-init-list中或者隐式地.你不能*初始化*在ctor体中的成员 (2认同)

Jos*_*eld 7

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

ProxyPiece::ProxyPiece(CubeGeometry& c)
  : cube(c)
{ }
Run Code Online (Sandbox Code Playgroud)

冒号后的所有内容都是初始化列表.这简单地说cube应该初始化c.

如您有它的cube成员是首先初始化默认,然后c拷贝分配给它.