【问题标题】:C++ operator overriding w/ arguments from 2 classesC++ 运算符覆盖 w/ 来自 2 个类的参数
【发布时间】:2012-11-04 20:03:37
【问题描述】:

我是面向对象编程的新手,我想知道是否可以为一个类创建一个运算符,该运算符将使用来自此类的参数和另一个由我声明的参数。

我必须解决的问题是在给定点上的线性平移。所以我创建了 PointLinearTranslation 类,基本上我想做的是创建一个运算符

Point operator* (Point p, LinearTranslation l) 

这需要Point p,翻译l然后返回Point。不过我遇到了奇怪的错误:Point operator*(int)’ must have an argument of class or enumerated typeLinearTranslation has not been declared

有可能吗?

好吧,我只发布一点,因为这是一种任务,所以我有 Point.h 类

抱歉造成混乱,但我正在尝试一切,但对我不起作用。

#include "LinearTranslation.h"
class Point {
public:
    int N;
    double* coordinates;

public:
    Point(int, double*);
    virtual ~Point();
    double operator[](int a);
    //friend Point operator*(LinearTranslation l);
    friend Point translation(LinearTranslation l);
};

LinearTranslation.h

#include "Point.h"

class LinearTranslation {
private:
    int N;
    double* vector;
    double** matrix;
public:
    //friend class Point;
    LTrans(int,double*,double**);
    LTrans(int);
    virtual ~LTrans();
    void write_vector();
    void write_matrix();
    LinearTranslation operator+(const LinearTranslation&);
    friend Point& translation(LTrans l, Point p);
    //friend Point& operator* (Point p, LTrans l);
};

【问题讨论】:

  • 听起来您在声明 LinearTransform 之前尝试声明此函数。另外,请发布代码。
  • 好的,我编辑了我的帖子,请帮助我!我被卡住了……
  • “尝试一切”听起来不是一个好策略。也许你应该尝试一件事,直到你做对为止。
  • 完全可以编写一个将两个不同的类作为参数的运算符。但是,发布的代码中没有任何内容可以做到这一点,因此很难为您尚未发布的代码提供帮助。
  • 您发布的第一行Point operator* (Point p, LinearTranslation l); 就是这样做的方法。你得到的奇怪错误一定来自你犯的其他错误。

标签: c++ class operator-keyword overriding


【解决方案1】:

在你的班级声明中:

//friend Point operator*(LinearTranslation l);

friend 运算符重载函数需要 两个 参数作为函数,您只需在代码中声明一个。友元函数最常见的示例是使用重载运算符 ,如下所示:

friend ostream& operator<<(ostream& output, const Point& p);

请注意,此函数将输出作为其第一个参数,将点作为其第二个参数。

您的解决方法是将操作数添加到函数中

friend Point operator*(LinearTranslation l, const int& MULT);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多