【问题标题】:use of an overloaded operator in a constructor?在构造函数中使用重载运算符?
【发布时间】:2019-12-01 21:30:11
【问题描述】:

我正在编写一个程序,你可以给一个对象一个整数,它会计算下一个更大的素数。任务是重载前缀运算符并在构造函数中使用它,这样如果我创建一个对象并给它数字 11,它应该存储下一个更大的素数 (13)。

我的运算符重载如下所示:

cPrimZahl& cPrimZahl::operator++()
{
    nextprim = prim;
    while (!is_Prime(nextprim))
    {
        ++nextprim;
        if (nextprim > 10000)
        {
            while (!is_Prime(nextprim))
            {
                --nextprim;
            }
            prim = nextprim;
            break;
        }
        prim = nextprim;
    }

    cout << "die naechst groessere Primzahl ist: " << prim << endl;

    return *this;
}

主要:

int main(){
    cPrimZahl obj(13);  // The object here is 13 now
    ++obj1;             // Here its 17

    return 0;
}

我的构造函数:

cPrimZahl::cPrimZahl(int prim_in)
{
    if (prim_in > maxprim)  // maxprim = 10000
    {
        cout << "Prime number is to big! Adjusting..." << endl;
        prim = 1;
    }

    else if (prim_in < 0)
    {
        cout << "Prime number can't be negative! Adjusting..." << endl;
        prim = 1;
    }

    prim = prim_in;
    ++prim;   // at this point i want it to increment to give me the next bigger prime number
}

我现在尝试了很多方法,但我总是得到一个常规增量......运算符重载出现在构造函数之前,但我也尝试将构造函数放在重载之前,但都不起作用。我还能做什么?

【问题讨论】:

  • 你可以在构造函数中调用++(*this)。它将在当前对象上调用前缀运算符。

标签: c++ constructor overloading operator-keyword


【解决方案1】:

在构造函数中prim 指的是prim 成员(可能是某种整数类型)。因此,++prim 对该整数类型使用了内置的预自增运算符,这将使 prim 成员加一。

您不想在 prim 成员上调用预增量运算符,而是在当前对象本身上调用。

可以使用*this获取当前对象,因此调用它的预增量运算符将使用++(*this);完成。

或者,您可以使用函数调用语法直接调用重载,将其视为普通成员函数:operator++();

【讨论】:

  • 谢谢,那是为我做的!终于了解了this操作符。 ^^
  • @marcopasta this 不是运算符,它是指向当前对象的指针,因此*this 是对当前对象的引用。
  • @marcopasta 您不应该在这里写 cmets 纯粹是为了说“谢谢”。请参阅here,了解当有人回答您的问题时您可以(但不必)做什么。
猜你喜欢
  • 2021-01-28
  • 1970-01-01
  • 2013-03-26
  • 1970-01-01
  • 2016-07-21
  • 1970-01-01
  • 2014-10-12
  • 2011-06-29
  • 1970-01-01
相关资源
最近更新 更多