簡體   English   中英

“沒有合適的默認構造函數可用”-為什么還要調用默認構造函數?

[英]“No appropriate default constructor available”--Why is the default constructor even called?

我已經看過其他一些與此有關的問題,但是我不明白為什么在我的情況下甚至應該調用默認構造函數。 我可以提供一個默認的構造函數,但是我想了解為什么這樣做以及它會產生什么影響。

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;
};

您的默認構造函數在此處隱式調用:

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
}

冒號后面的東西稱為成員初始化列表

順便說一句,如果我是您,我將采用const CubeGeometry& c而不是CubeGeomety& c作為參數。

構造函數開始時會進行成員初始化。 如果在構造函數的成員初始化列表中未提供初始化程序,則將默認構造該成員。 如果要復制用於初始化成員cube構造函數,請使用成員初始化列表:

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

冒號后面的所有內容都是初始化列表。 這只是說cube應使用c初始化。

如您所願,首先將cube成員默認初始化,然后將c 復制分配給它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM