【发布时间】:2022-01-21 16:11:09
【问题描述】:
我目前正在使用 Visual Studio Community Edition 2019 在 C++ 中实现一个简单的 2D 矢量类 Vector2f。
当我尝试在一个方法中返回一个新建的,比如:
return Vector2f((this->x/sum),(this->y/sum);
我得到一个提示:
Vector2f 没有合适的复制构造函数
和一个编译错误:
'return': 无法从 'Vector2f' 转换为 'Vector2f'
我已经从头开始重写了几次课程,但似乎仍然出现错误。我不明白,到底出了什么问题?
Vector2f_struct.h
#pragma once
#ifndef PMP_VECTOR2F_STRUCT__H
#define PMP_VECTOR2F_STRUCT__H
namespace pmp
{
struct Vector2f
{
/* Elements */
float x;
float y;
/* Methods */
// Constructors & Destructor
Vector2f();
Vector2f(float i, float j);
Vector2f(Vector2f& og);
virtual ~Vector2f();
// Unary Operators
float magnitude();
Vector2f normal();
};
};
#endif
Vector2f_struct.cpp
#include "pmp_Vector2f_struct.h"
#ifndef PMP_VECTOR2F_STRUCT__CPP
#define PMP_VECTOR2F_STRUCT__CPP
/* Dependencies */
#include <math.h>
namespace pmp
{
Vector2f::Vector2f()
{
this->x = 0.0f;
this->y = 0.0f;
return;
};
Vector2f::Vector2f(float i, float j)
{
this->x = i;
this->y = j;
return;
};
Vector2f::Vector2f( Vector2f& og )
{
this->x = og.x;
this->y = og.y;
return;
};
Vector2f::~Vector2f()
{
this->x = 0.0f;
this->y = 0.0f;
return;
};
float Vector2f::magnitude()
{
float c2 = (this->x * this->x) + (this->y * this->y);
return sqrt(c2);
};
Vector2f Vector2f::normal()
{
float sum = this->x + this->y;
return Vector2f(this->x / sum, this->y / sum); // Error here.
};
};
#endif
【问题讨论】:
-
你返回一个临时对象,r-value不能绑定到Vector2f&,但是可以绑定到const Vector2f&。 Copy constructors
-
是的,您没有有效的复制构造函数,因为您忘记了参数的
const限定符。在线查找复制构造函数的示例。 -
此外,没有理由自己定义复制构造函数,因为编译器提供的默认构造函数应该和你的一样。你的析构函数也是不需要的。
-
摆脱
Vector2f(Vector2f& og);,你不需要它。很可能你也不需要析构函数,除非你真的需要它是虚拟的。在这种情况下,我会将其定义为virtual ~Vector2f() {}。将内部数字归零没有多大意义,可能会被优化掉。 -
啊,谢谢大家!我全忘了!
标签: c++ struct constants copy-constructor