【问题标题】:"No appropriate default constructor available"--Why is the default constructor even called?“没有合适的默认构造函数可用”——为什么还要调用默认构造函数?
【发布时间】:2013-03-20 13:27:25
【问题描述】:

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

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


    【解决方案1】:

    你的默认构造函数在这里被隐式调用:

    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&amp; c 而不是 CubeGeomety&amp; c。

    【讨论】:

    • 为了更清楚,也许您可​​以在您的“与 sn-p 相同”中将 cube = c; 更改为 cube.operator=(c);。这将有助于解释分配不会(从语言角度)重新初始化cube。
    • 那么任何成员变量的所有默认构造函数都会在包含类的构造函数之前被调用? (是的,我会将其设为 const :))
    • @AABoucher:是的。虽然不是 before 构造函数,而是在它的开头。 Tor-init-list 是构造函数调用的一部分。但是,是的,一旦你输入了构造函数的 body,所有的成员都会被初始化——无论是在 ctor-init-list 中显式地还是隐式地。您不能初始化 ctor body 中的成员
    • @ArmenTsirunyan 非常感谢您的明确解释。我现在明白了。
    【解决方案2】:

    在构造函数开始时发生成员初始化。如果您没有在构造函数的成员初始化列表中提供初始化器,则该成员将被默认构造。如果要复制构造函数用于初始化成员cube,请使用成员初始化列表:

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

    冒号后面的都是初始化列表。这只是说cube 应该用c 初始化。

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

    【讨论】:

    • 我明白了,感谢初始化列表/复制分配的解释!
    猜你喜欢
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多