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

标签 c++ class vector overloading

我最近开始学习 C++,现在我正在尝试制作一个简单的 vector 类作为练习。但不知何故,我的代码似乎无法正常工作。

#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
};

关于c++ - C++ 类构造中的奇怪错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44020674/

相关文章:

python实例变量作为可选参数

java - "Class.forName()"和 "Class.forName().newInstance()"有什么区别?

C++ 未声明的类错误

C++ Vector.erase() 导致段错误

c++ - 如何从 C++ 中的字符指针获取 Java 字符串

c++ - 从非主线程加载的 VAO 崩溃

c++ - 如何使用 MPI 库为进程子集调用 (c++) 函数?

c++ - C++-创建bmp文件并通过createwindow()显示它的问题

c++ - Boost::Container::Vector with Enum Template Argument - 不是合法的基类

c++ - 如何在C++中取每第n个元素的平均值