【问题标题】:C++ Type error with Object versus Object reference对象与对象引用的 C++ 类型错误
【发布时间】:2010-05-17 04:19:15
【问题描述】:

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

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

当我使用 g++ version 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 添加了一个复制构造函数(见下文),但没有帮助。

矢量.h:

Vector(const Vector& other);

矢量.cpp:

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

【问题讨论】:

  • 关于“在 Visual Studio 中工作”问题,Visual C++ 有一个语言扩展,允许将临时引用绑定到非常量引用。您可以在项目属性中禁用语言扩展,如果您想编写可移植代码,这样做可能是个好主意。

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


【解决方案1】:

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

如果一个函数不修改引用的参数,那么它应该接受一个 const 引用。因此,您的点积函数应声明为:

double Vector::dotProduct(const Vector&);

【讨论】:

  • 谢谢,这解决了问题。感谢其他提出类似答案的人。
【解决方案2】:

Vector 临时变量无法正确转换为Vector&amp;——我猜 MSVC++ 在这里太松懈了。为什么containsdotProduct 采取Vector&amp; 他们从来不需要修改 arg?!他们应该接受const Vector&amp;!我认为 gcc 在这里正确地指导你。

【讨论】:

  • 我相信VC++会发出警告,但它仍然会让它编译,所以是的,它有点松懈。
【解决方案3】:

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

【讨论】:

    【解决方案4】:

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

    【讨论】:

    • 另一个向量是隐式参数(this)。
    • @Matthew,对……没想到。出于某种原因,我没有看到“normalVector”。在调用之前。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多