在返回结构C++中获取"No valid copy constructor"



我目前正在使用Visual Studio Community Edition 2019在C++中实现一个简单的2D矢量类Vector2f

当我试图返回方法中新建的一个时,例如:

return Vector2f((this->x/sum),(this->y/sum);

我得到了一个提示:

没有适合Vector2f 的复制构造函数

和编译时的错误:

"回车":无法从"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

复制构造函数的参数具有非常量引用类型

Vector2f(Vector2f& og);

在成员函数正常情况下,返回一个被复制的临时对象。不能将临时对象与非常量左值引用绑定。

像一样重新声明复制构造函数

Vector2f(const Vector2f& og);

或者只是删除它的明确声明。在这种情况下,编译器会为您生成它。

请注意构造函数和析构函数中的返回语句是多余的。

相关内容

最新更新