使用Object与Object引用的C ++类型错误

时间:2010-05-17 04:19:15

标签: c++ visual-studio g++ pass-by-reference

我有以下功能(在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&amp;。

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

我确认这有效:

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) {
}

4 个答案:

答案 0 :(得分:2)

您的问题是point - position的结果是一个临时对象,不能绑定到非const引用。

如果函数没有修改引用所引用的参数,那么它应该采用const引用。你的点积函数应该声明为:

double Vector::dotProduct(const Vector&);

答案 1 :(得分:2)

Vector临时变量无法正确转换为Vector& - 我想MSVC ++在这里太宽松了。为什么containsdotProduct需要Vector&他们从未真正需要修改 arg ?!他们应该const Vector&!我认为gcc在这里正确引导你。

答案 2 :(得分:1)

point - position似乎创建了Vector类型的临时对象,并且您正在尝试将临时对象传递给需要引用的函数。这个不允许。尝试将其声明为dotProduct(const Vector&);

答案 3 :(得分:1)

问题是你的dotProduct函数应该通过const引用来获取它的参数。