“没有适当的默认构造函数可用” - 为什么默认构造函数甚至被调用?
我已经看过关于这个的一些其他问题,但我不明白为什么一个默认的构造函数甚至应该在我的情况下调用。我可以提供一个默认的构造函数,但我想知道为什么它这样做和它影响。
I've looked at a few other questions about this, but I don't see why a default constructor should even be called in my case. I could just provide a default constructor, but I want to understand why it is doing this and what it affects.
error C2512: 'CubeGeometry' : no appropriate default constructor available
我有一个名为ProxyPiece的类有CubeGeometry的成员变量。构造函数应该接受一个CubeGeometry并将其分配给成员变量。这是标题:
I have a class called ProxyPiece with a member variable of CubeGeometry.The constructor is supposed to take in a CubeGeometry and assign it to the member variable. Here is the header:
#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)
{
}
多维数据集几何的标题看起来像这样。我没有意义使用默认构造函数。我需要它吗?:
the header for cube geometry looks like this. It doesn't make sense to me to use a default constructor. Do I need it anyways?:
#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;
};
您的默认构造函数在这里被隐含地调用:
Your default constructor is implicitly called here:
ProxyPiece::ProxyPiece(CubeGeometry& c)
{
cube=c;
}
您需要
ProxyPiece::ProxyPiece(CubeGeometry& c)
:cube(c)
{
}
否则你的ctor等效于
Otherwise your ctor is equivalent to
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
如果我是你。
Incidentally, I would take the argument as const CubeGeometry& c
instead of CubeGeomety& c
if I were you.