c++ - C++中的重载

标签 c++ operator-overloading

我不确定我是否正确地进行了重载。

...\point.h(42):错误 C2061:语法错误:标识符“Vec3” 点运算符 +(Vec3 a) const;

这是我的 .h 文件:

    #include <fstream>
    #include <iostream>
    #include "vec3.h"

    using std::ofstream;
    using std::ifstream;
    using std::cout;
    using std::cin;
    using std::endl;
    using namespace std;

    #ifndef POINT_H
    #define POINT_H

    //Define ourselves a basic 2D point class
    class Point
    {

        friend ofstream& operator <<(ofstream& output, const Point& p);
        friend ifstream& operator >>(ifstream& input, Point& p);
\    
        public:

        Point();
        Point(double _x, double _y);
        Point(double _x, double _y, double _z);

        double x,y,z;

        //Operators
        Point operator -(Point a) const;
        Point operator /(double s) const;
        Point operator *(double s) const;

        // Used to do vector point addition
        Point operator +(Vec3 a) const;

    };

    #endif

这是我的 .cpp 文件

#include "point.h"

Point::Point(double _x, double _y, double _z)
{
    x= _x;
    y= _y;
    z= _z;
}

Point :: Point()
{
    x = 0.0;
    y = 0.0;
    z = 0.0;
}

Point::Point(double _x, double _y)
{
    x= _x;
    y= _y;
    z= 0;
}

    Point Point::operator -(Point a) const
    {
        return Point(x-a.x, y-a.y, z-a.z);
    }

    Point Point::operator /(double s) const
    {
        return Point(x/s, y/s, z/s);
    }

    Point Point::operator *(double s) const
    {
        return Point(x*s, y*s, z*s);
    }


// Vector Point Addition
    Point Point::operator +(Vec3 a) const
    {
        return Point(x+a.x, y+a.y, z+a.z);
    }

    ofstream& operator <<(ofstream& output, const Point& p)
    {
        output << p.x << " " << p.y << " " << p.z << "\n";
        return output;
    }

    ifstream& operator >>(ifstream& input, Point& p)
    {
        input >> p.x >> p.y >> p.z;
        return input;
    }

这是Vec3.h

    #ifndef VEC3_H
#define VEC3_H

#include "point.h"

class Vec3
{
    friend ofstream& operator <<(ofstream& output, const Vec3& p);
    friend ifstream& operator >>(ifstream& input, Vec3& p);

    public: 
    Vec3();
    Vec3(double _x, double _y);
    Vec3(double _x, double _y, double _z);

    double x,y,z;

    //Operators
    Vec3 operator -(Vec3 a) const;
    Vec3 operator /(double s) const;
    Vec3 operator *(double s) const;

    // Used to do vector Vec3 addition
    Vec3 operator +(Vec3 a) const;
    Point operator +(Point a) const;

};

#endif

最佳答案

vec3.h包含point.hpoint.h包含vec3.h。您需要通过前向声明其中一个类来移除循环依赖。

关于c++ - C++中的重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3939203/

相关文章:

c++ - 错误 C2666 类似重载

c++ - 将整数数组转换为类数组

c++ - 对象删除 : use parent or not

c++ - setContextProperty() 在这种情况下如何失败?

c++ - C++字符串程序错误

c++ - 如何以有效的方式将输入参数传递给函数

struct - 允许在 D 中进行 [i] 和 .xyz 操作的快速向量结构?

c++ - Winsock send() 总是在服务器中返回错误 10057

r - R 中 S4 对象的总和

c++ - 当操作的变量是 const 时,如何修复括号/索引运算符重载?