开发者

C++ Type error with Object versus Object reference

开发者 https://www.devze.com 2022-12-30 06:44 出处:网络
I have the following function (which worked in Visual Studio): bool Plane::contains(Vector& point){

I have the following function (which worked in Visual Studio):

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

When I compile it using g++ version 4.1.2 , I get the following error:

Plane.cpp: In member function âvirtual bool Plane::contains(Vector&)â:
Plane.cpp:36: error: no matching function fo开发者_运维问答r call to âVector::dotProduct(Vector)â
Vector.h:19: note: candidates are: double Vector::dotProduct(Vector&)

So as you can see, the compiler thinks (point-position) is a Vector but it's expecting Vector&.

What's the best way to fix this?

I verified that this works:

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

But I was hoping for something a little bit cleaner.

I heard a suggestion that adding a copy constructor might help. So I added a copy constructor to Vector (see below), but it didn't help.

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


Your problem is that the result of point - position is a temporary object, which cannot be bound to a non-const reference.

If a function does not modify an argument taken by reference, then it should take a const reference. Ergo, your dot product function should be declared as:

double Vector::dotProduct(const Vector&);


A Vector temporary variable can't properly be converted to a Vector& -- I guess MSVC++ is being too lax here. Why do contains and dotProduct take a Vector& where they never really need to modify the arg?! They should take a const Vector&! I think gcc is guiding you correctly here.


point - position seems to creates temporary object of type Vector and you are trying to pass temporary to a function that requires reference. It is not allowed. Try declare it as dotProduct(const Vector&);


The problem is that your dotProduct function should take its parameter by const reference.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号