【问题标题】:在返回结构时在 C++ 中获取“没有有效的复制构造函数”
【发布时间】: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&amp; og);,你不需要它。很可能你也不需要析构函数,除非你真的需要它是虚拟的。在这种情况下,我会将其定义为virtual ~Vector2f() {}。将内部数字归零没有多大意义,可能会被优化掉。
  • 啊,谢谢大家!我全忘了!

标签: c++ struct constants copy-constructor


【解决方案1】:

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

Vector2f(Vector2f& og);

在成员函数 normal 中返回一个被复制的临时对象。您不能将临时对象绑定到非常量的左值引用。

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

Vector2f( const Vector2f& og);

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

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

【讨论】:

    猜你喜欢
    • 2021-03-23
    • 2015-11-12
    • 2019-08-12
    • 2010-12-11
    • 2014-04-15
    • 2011-07-15
    • 2015-07-24
    • 1970-01-01
    • 2013-10-03
    相关资源
    最近更新 更多