重载 * 运算符不会给出匹配错误

Overloading * operator gives no match error

本文关键字:错误 运算符 重载      更新时间:2023-10-16

嗨,我正在尝试创建一个光线追踪器来渲染多边形的、基于三角形的模型。

我在 point3d.h 中有一个包含 x、y 和 z 坐标的点 3D 结构。

#ifndef __POINT3D_H__
#define __POINT3D_H__
#include <iostream>
using namespace std;
struct Point3D
{
    double x;
    double y;
    double z;
    Point3D() : x(0.0), y(0.0), z(0.0) {}
    Point3D(const double & nx, const double & ny, const double & nz) : x(nx), y(ny), z(nz) {}
    Point3D operator+(const Point3D & rhs) const { 
     return Point3D(x + rhs.x, y + rhs.y, z + rhs.z); }
    Point3D operator-(const Point3D & rhs) const { 
     return Point3D(x - rhs.x, y - rhs.y, z - rhs.z); }
    Point3D operator*(double val) const { 
     return Point3D(x * val, y * val, z * val); }
    Point3D operator/(double val) const { 
     return Point3D(x / val, y / val, z / val); }
    Point3D operator+=(const Point3D & rhs) { 
     x += rhs.x; y += rhs.y; z += rhs.z; return *this; }
    Point3D operator-=(const Point3D & rhs) { 
     x -= rhs.x; y -= rhs.y; z -= rhs.z; return *this; }
    Point3D operator*=(double val) { 
     x *= val; y *= val; z *= val; return *this; }
    Point3D operator/=(double val) { 
     x /= val; y /= val; z /= val; return *this; }
    void print() {
     cout << '(' << x << ',' << y << ',' << z << ')'; 
    }
};
#endif

这是我尝试使用 * 运算符将多个两个 Point3D 放在一起的地方

Point3D phong(Point3D mColor, Point3D lColor, Point3D L, Point3D N, Point3D R, Point3D V) 
{
 Point3D k(1.0, 1.0, 1.0);
 Point3D ambient = mColor * k.x;
 Point3D diffuse_angle = ((N * L) / (length(N) * length(L)));
 Point3D diffuse = lColor * k.y * diffuse_angle; 
 Point3D specular_angle = ((R * V) / (length(R) * length(V)));
 double specular_x = pow(specular_angle.x, 100.0);
 double specular_y = pow(specular_angle.y, 100.0);
 double specular_z = pow(specular_angle.z, 100.0);
 Point3D specular_power(specular_x, specular_y, specular_z);
 Point3D specular = lColor * k.z * specular_power;
 return ambient + (lColor * (diffuse + specular)); 
}

当我尝试将多个两个 Point3D 放在一起时,我收到不匹配错误。这是代码失败的地方。我觉得这是一个简单的错误,但我无法弄清楚。我包含Point3d头文件如下:#include"point3d.h"。

Point3D operator*(double val) const

您只有此版本,Point3D * double,仅此而已,但是您正在尝试使用此运算符进行Point3D * Point3DPoint3D不能从double隐式构造,所以这就是你出现编译错误的原因。

Point3D operator*(double val) const { 

这是用于乘法Point3D * double。并通过

N * L

你正在尝试做Point3D * Point3D.

您可以通过为类提供适当的operator*或通过单参数构造函数提供从双精度到类的转换来纠正此问题。虽然我更喜欢前者。

你应该需要一个这样的函数

Point3D operator *(Point3D &temp) const {
}

由于您没有将两个 3d 点相乘的函数,因此会出现错误。尝试添加此函数。

你需要

一个函数来操作Point3D * Point3D,它不能适应Point3D::operator*(double val)的调用。如:

Point3D operator*(const Point3D & rhs) const {
    return Point3D(x * rhs.x, y * rhs.y, z * rhs.z); }