C 如何在另一类中使用操作员过载

C++ how to use operator overload in another class

本文关键字:一类 操作员      更新时间:2023-10-16
class  vec3{
float x;
float y;
float z;
const vec3 & operator= (const vec3 &rvec3)
{
    x = rvec3.x;
    y = rvec3.y;
    z = rvec3.z;
    return *this;
}  };
class vec2{
vec3 vetex;
vec3 normal;
const vec2 & operator = (const vec2 &rvec2)
{
    vetex = rvec2.vetex;
    normal= rvec2.normal;
    return *this;
} };

编译器显示错误" Operator ="是'VEC3'的私人成员。怎么会发生?

更改为

class  vec3{
float x;
float y;
float z;
public:
const vec3 & operator= (const vec3 &rvec3)
{
    x = rvec3.x;
    y = rvec3.y;
    z = rvec3.z;
    return *this;
}  };

操作员方法已公开,从外部代码可以看到。
除了类vec2operator=的定义外,这是不必要的,因为它是此类操作员的默认行为。顺便说一句,vec3中的operator=也不需要。

也许您应该从类别更改为结构。

默认情况下,C 中的类成员是私有的。

要允许外部代码查看操作员,您需要将其指定为公共。

class  vec3{
float x;
float y;
float z;
public:
const vec3 & operator= (const vec3 &rvec3)
{
    x = rvec3.x;
    y = rvec3.y;
    z = rvec3.z;
    return *this;
}  };