gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:40:08 26 4
gpt4 key购买 nike

我最近开始学习 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com