gpt4 book ai didi

对象与对象引用的 C++ 类型错误

转载 作者:搜寻专家 更新时间:2023-10-31 00:22:52 25 4
gpt4 key购买 nike

我有以下功能(在 Visual Studio 中有效):

bool Plane::contains(Vector& point){
return normalVector.dotProduct(point - position) < -doubleResolution;
}

当我使用 g++ 版本 4.1.2 编译它时,出现以下错误:

Plane.cpp: In member function âvirtual bool Plane::contains(Vector&)â:
Plane.cpp:36: error: no matching function for call to âVector::dotProduct(Vector)â
Vector.h:19: note: candidates are: double Vector::dotProduct(Vector&)

如您所见,编译器认为 (point-position) 是一个 Vector 但它期待 Vector&。

解决此问题的最佳方法是什么?

我验证了这有效:

Vector temp = point-position;
return normalVector.dotProduct(temp) < -doubleResolution;

但我希望有一些更干净的东西。

我听说添加复制构造函数可能会有帮助。所以我向 Vector 添加了一个复制构造函数(见下文),但它没有帮助。

vector .h:

Vector(const Vector& other);

vector .cpp:

Vector::Vector(const Vector& other)
:x(other.x), y(other.y), z(other.z), homogenous(other.homogenous) {
}

最佳答案

你的问题是 point - position 的结果是一个临时对象,不能绑定(bind)到非常量引用。

如果函数不修改通过引用获取的参数,那么它应该采用 const 引用。因此,您的点积函数应声明为:

double Vector::dotProduct(const Vector&);

关于对象与对象引用的 C++ 类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2846644/

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