代码之家  ›  专栏  ›  技术社区  ›  muddybruin

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

  •  2
  • muddybruin  · 技术社区  · 14 年前

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

    如您所见,编译器认为(点位置)是一个向量,但它期望向量&。

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

    我证实这是可行的:

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

    但我希望能有点干净。

    我听到一个建议,添加一个复制构造函数可能会有所帮助。所以我在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 回复  |  直到 14 年前
        1
  •  2
  •   James McNellis    14 年前

    你的问题是 point - position 是临时对象,不能绑定到非常量引用。

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

    double Vector::dotProduct(const Vector&);
    
        2
  •  2
  •   Alex Martelli    14 年前

    Vector 临时变量无法正确转换为 Vector& --我想MSVC++在这里太松懈了。为什么 contains dotProduct 拿一个 矢量与放大器; 他们根本不需要去的地方 修改 ARG?!他们应该 const Vector& !我认为海湾合作委员会正在正确地指导你。

        3
  •  1
  •   Kirill V. Lyadvinsky    14 年前

    point - position 似乎创建了类型为的临时对象 Vector 您试图将temporary传递给需要引用的函数。这是不允许的。试着把它声明为 dotProduct(const Vector&);

        4
  •  1
  •   Michael Aaron Safyan    14 年前

    问题是您的dotproduct函数应该通过const引用获取其参数。