我正在调试一个3D矢量代码,但得到以下错误
/usr/bin/g++ -fdiagnostics-color=always -g /home/fangrui/vectorFEM/vectorFEM/main.cpp -o /home/fangrui/vectorFEM/vectorFEM/main
In file included from /home/fangrui/vectorFEM/vectorFEM/constant.h:6:0,
from /home/fangrui/vectorFEM/vectorFEM/mesh.h:2,
from /home/fangrui/vectorFEM/vectorFEM/edgenedelec.h:2,
from /home/fangrui/vectorFEM/vectorFEM/main.cpp:1:
/home/fangrui/vectorFEM/vectorFEM/cvector3D.h: In function ‘cvector operator*(double, cvector)’:
/home/fangrui/vectorFEM/vectorFEM/cvector3D.h:39:10: error: cannot bind non-const lvalue reference of type ‘cvector&’ to an rvalue of type ‘cvector’
return cvector(x1*x2.x, x1*x2.y, x1*x2.z);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
...
这是cvector3D.h
文件中的一个问题,但我不明白这个错误以及应该进行什么样的更改。除了上面的错误,还有一个关于friend
的警告:
class "cvector" has no suitable copy constructorC/C++(334)
下面是cvector3D.h
的原始代码
# ifndef CVECTOR3D_H
# define CVECTOR3D_H
#include<cmath>
#include<ostream>
#include<iomanip>
using namespace std;
/*A three-dimensional real vector class is defined to facilitate numerical calculations*/
class cvector
{
public:
double x, y, z;
//Construct function
cvector(double _x, double _y, double _z){ x = _x; y = _y; z = _z; }
//Copy the constructor
cvector(cvector &pt){ x = pt.x; y = pt.y; z = pt.z; }
cvector(){ x = 0; y = 0; z = 0; }
~cvector(){};
//Operator overloading
cvector operator +();
cvector operator -(); //The vector is negated
friend ostream &operator<<(ostream &os, const cvector &x1);
cvector operator +(cvector x1);
cvector operator -(cvector x1);
cvector operator *(double x1);
cvector operator /(double x1);
cvector &operator =(cvector x1);
cvector &operator +=(cvector x1);
cvector &operator -=(cvector x1);
cvector &operator *=(double x1);
cvector &operator /=(double x1);
int operator ==(cvector x1);
int operator !=(cvector x1);
friend cvector operator *(double x1, cvector x2) {
return cvector(x1*x2.x, x1*x2.y, x1*x2.z);
}
//Member functions
double dist(cvector x1);
cvector unit();
double norm();
friend cvector cross(cvector x1, cvector x2)
{
return cvector(x1.y*x2.z - x1.z*x2.y, x1.z*x2.x - x1.x*x2.z, x1.x*x2.y - x1.y*x2.x);
}
friend double dot(cvector x1, cvector x2)
{
return (x1.x*x2.x + x1.y*x2.y + x1.z*x2.z);
}
} ;
# endif
1条答案
按热度按时间zkure5ic1#
cvector
复制构造函数格式错误**正确的形式是
cvector(const cvector& cvec)
。当好友功能
被称为
cvector
的构造函数。在构造对象被copy返回后立即调用复制构造函数,但是刚刚创建的cvector&
类型的左值,即non-const
不能转换为cvector
类型的右值。这是因为非常量引用参数,例如
int&,
只能引用“lvalue”,这是一个命名变量。在这种情况下,创建的对象不是命名变量。