【问题标题】:C++ Operator overloading using pointers to class使用指向类的指针的 C++ 运算符重载
【发布时间】:2015-01-19 17:50:40
【问题描述】:

这是我的课:

class B : public A{
private:
double r;


public:
B(){};
B(double x_, double y_, double r_){
    x1 = x_; y1 = y_; r = r_;
};
~B(){};
B operator+(const B&  other)
{
    double result_r = r + other.r;
    return B(x1, y1, result_r);
}
B operator*(const B&  other)
{
    double result_r = this->r * other.r;
    return B(x1, y1, result_r);
}
int operator<(const B&  other){
    if (this->r<other.r)return 1; else return 0;
}
int operator>(const B&  other){
    if (this->r>other.r)return 1; else return 0;
}
};

A 类是抽象的,这就是我声明 B 的方式:

A*a = new B(10, 10, 10);
A*b = new B(20, 20, 20);

虽然(a&lt;b) 之类的东西确实有效,但A*c=a+b; 无效。 如果我不使用指向 A 的指针,它确实有效,并且

【问题讨论】:

  • 缩进你的代码。然后说用它不起作用是什么意思?例如逻辑错误或语法错误。
  • 用大写字母开头的句子和使用标点符号和拼写太费力了?好像写到一半真的累了。
  • 对不起,它只是在视觉 2013 error C2110: '+' : cannot add two pointers 和 IntelliSense: expression must have integral or unscoped enum type 中返回这些错误

标签: c++ class pointers operators overloading


【解决方案1】:

你说:

虽然(a&lt;b) 之类的东西确实有效,但A*c=a+b; 无效。

(a&lt;b) 有效,因为编译器知道如何比较两个指针。这并不意味着它会解析为bool B::operator&lt;(const B&amp;)。

A*c=a+b; 不起作用,因为编译器现在不知道如何添加两个 B* 对象。

要使用您定义的运算符重载函数,您必须使用 B 类型的对象,而不是指向 B 类型的对象的指针。

您可以通过以下方式显式调用运算符函数:

B* b1Ptr = new B;
B* b2Ptr = new B;
B b3 = b1Ptr->operator+(*b2Ptr);

但这不是你通过使用得到的结果

B b3 = b1Ptr + b2Ptr;

你也可以使用:

B b3 = *b1Ptr + *b2Ptr;

【讨论】:

    【解决方案2】:

    A* c 声明一个指针。 a+b 的结果是 B 类型。因此编译器会告诉您不能将 B 类型的对象分配给指针。为什么需要指针?

    只需使用A c = a + b。

    如果你真的想使用指针,那么做

    A tmp = a + b;
    A* c = &tmp;
    

    或直接

    A* c = new B(a+b);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      相关资源
      最近更新 更多