quot;No appropriate default constructor availablequot;--Why is the default constructor even called?(“没有合适的默认构造函数可用--为什么甚至调用默认构造函数?)
问题描述
我已经查看了其他一些关于此的问题,但我不明白为什么在我的情况下甚至应该调用默认构造函数.我可以只提供一个默认构造函数,但我想了解它为什么这样做以及它会影响什么.
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.
这篇关于“没有合适的默认构造函数可用"--为什么甚至调用默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“没有合适的默认构造函数可用"--为什么甚至调用默认构造函数?


基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01