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

问题描述 投票:12回答:2

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

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;
};
c++ constructor member default-constructor
2个回答
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


6
投票

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

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

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

如你所知,cube成员首先默认初始化,然后c被复制分配给它。

© www.soinside.com 2019 - 2024. All rights reserved.