|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
我定义了一个向量类,声明是这样:
- class Vector
- {
- public:
- unsigned short dimensions = 0;
- double *values = nullptr;
- Vector(const Vector &);
- Vector(unsigned short, double []);
- ~Vector();
- Vector operator+(const Vector &);
- Vector operator+(const double);
- Vector operator-();
- Vector operator-(const Vector &);
- Vector operator-(const double);
- Vector operator*(const Vector &);
- Vector operator*(const double);
- Vector operator/(const double);
- double dot(const Vector &);
- double length();
- Vector length(const int);
- double angle(const Vector &);
- };
复制代码
在 Vector::angle 函数的实现中编译器发出了错误:
- #include <cmath>
- double Vector::angle(const Vector &other)
- {
- return acos(this->dot(other) / (this->length() * other.length()));
- };
复制代码
错误是这么说的:
line 4: return acos(this->dot(other) / (this->length() * other.length()));
没有与参数列表和对象匹配的 重载函数 "Vector::length" 实例(对象包含阻止匹配的类型限定符) C/C++(1087)
这是怎么回事,是 const 的问题吗?应该怎样修复?
是的,错误是由于 const 修饰符引起的。在 C++ 中,如果成员函数被声明为 const ,表示它不会修改对象的状态,即它不会修改成员变量的值。在你的情况下,编译器指出了问题: Vector::length 函数没有一个 const 修饰符的重载版本,所以无法在 Vector::angle 函数中调用 this->length() 和 other.length() 。
要修复这个问题,你需要在 Vector::length 函数声明中添加 const 修饰符,表示它是一个只读函数,不会修改对象的状态。修改方式如下:
- class Vector
- {
- public:
- // ... 其他成员函数
- double length() const; // 在这里添加 const 修饰符
- };
复制代码
然后,在实现文件中对应的函数定义也要加上 const 修饰符:
- #include <cmath>
- double Vector::length() const // 在这里添加 const 修饰符
- {
- // 函数实现
- }
复制代码
通过在 Vector::length 函数声明和定义中添加 const 修饰符,编译器就能够正确地识别 length() 函数为只读函数,并允许在 Vector::angle 函数中调用 this->length() 和 other.length() 了。
这样,问题就会得到解决,编译器不再报告关于缺少 const 修饰符的错误,而你的代码也能正确运行。
|
|