繁体   English   中英

C ++类构造中的奇怪错误

[英]Strange error in c++ class construction

我最近开始学习c ++,现在正尝试制作一个简单的向量类作为练习。 但是我的代码似乎不起作用。

#include <iostream>
#include <cmath>
class Vec2
{
public:
    float x1;
    float x2;
    Vec2(float a,float b):x1(a),x2(b){}
    float norm()
    {
        return sqrt(x1*x1+x2*x2);
    }
    Vec2 operator+(const Vec2 &v)
    {
        Vec2 newv;
        newv.x1=this->x1+v.x1;
        newv.x2=this->x2+v.x2;
        return newv;
    }
};
int main()
{
    Vec2 v1(3,4);
    Vec2 v2(4,5);
    Vec2 v3=v1+v2;
    std::cout << v1.x1 << std::endl;
    std::cout << v1.norm() << std::endl;
    std::cout << v3.x1 << std::endl;
    return 0;
}

我使用eclipse作为编辑器,编译时出现此错误:

11:13:04 **** Incremental Build of configuration Debug for project Vec2 ****
make all 
Building file: ../Vec2.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"Vec2.d" -MT"Vec2.o" -o "Vec2.o" "../Vec2.cpp"
../Vec2.cpp: In member function ‘Vec2 Vec2::operator+(const Vec2&)’:
../Vec2.cpp:15:11: error: no matching function for call to ‘Vec2::Vec2()’
      Vec2 newv;
           ^~~~
../Vec2.cpp:8:2: note: candidate: Vec2::Vec2(float, float)
  Vec2(float a,float b):x1(a),x2(b){}
  ^~~~
../Vec2.cpp:8:2: note:   candidate expects 2 arguments, 0 provided
../Vec2.cpp:3:7: note: candidate: constexpr Vec2::Vec2(const Vec2&)
 class Vec2
       ^~~~
../Vec2.cpp:3:7: note:   candidate expects 1 argument, 0 provided
../Vec2.cpp:3:7: note: candidate: constexpr Vec2::Vec2(Vec2&&)
../Vec2.cpp:3:7: note:   candidate expects 1 argument, 0 provided
make: *** [subdir.mk:20: Vec2.o] Error 1

11:13:05 Build Finished (took 422ms)

我怀疑操作员超载是这里的罪魁祸首,但我似乎无法使其运行。 任何想法将不胜感激!

您的课程缺少默认的构造函数。 只需添加一个就可以了

class Vec2
{
public:
    float x1;
    float x2;
    Vec2() {}  // default constructor
};

问题不在于运算符重载。 该错误消息将帮助您了解这是构造函数问题。

根据参考,如果您有用户定义的构造函数,则该类的默认构造函数不存在。 因此,您的程序在构造函数中需要参数,而您尚未提供。

解决方法是定义一个默认的构造函数,以及已经定义的构造函数。 这样,您可以同时使用两者。

Vec2() {}

希望这可以帮助!

您可以创建默认构造函数

Vec2() {}

或者您可以将第15-17行更改为

Vec2 newv(this->x1+v.x1, newv.x2=this->x2+v.x2);

我们不需要此类的默认构造函数。 这意味着用户不能在没有x,y参数的情况下创建对象。我想,如果您打算以这种方式使用户成为一个很好的理由。

#include <iostream>
#include <cmath>
class Vec2
{
public:
    float x1;
    float x2;
    Vec2(float a,float b):x1(a),x2(b){}
    float norm()
    {
        return sqrt(x1*x1+x2*x2);
    }
    Vec2 operator+(const Vec2 &v)
    {
        float x1=this->x1+v.x1;
        float x2=this->x2+v.x2;
        Vec2 newv(x1,x2);
        return newv;
    }
};
int main()
{
    Vec2 v1(3,4);
    Vec2 v2(4,5);
    Vec2 v3=v1+v2;
    std::cout << v1.x1 << std::endl;
    std::cout << v1.norm() << std::endl;
    std::cout << v3.x1 << std::endl;
    return 0;
}

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM