从同一类的成员函数返回一个对象

Returning an object from a member function of the same class

本文关键字:成员 函数 返回 一个对象 一类      更新时间:2023-10-16

我遇到了下面的程序:

class Counter { 
 protected:         
  unsigned int count;  
 public:  
  Counter(): count(0) {}   
  Counter(int c): count(c) {}   
  unsigned int get_count() { return count; }  
  Counter operator++() { return Counter(++count); }  
};  

最后一个成员函数(Counter(++count))做什么?

我想你想为你的类实现operator++,那应该实现为:

Counter & operator++()
{
   ++count;
   return *this;
}

现在的问题是它是做什么的?它做预增量。现在你可以写++counter,这将调用上面的操作符重载,并在内部将变量count增加1。

的例子:

Counter counter(1);
++counter;
std::cout << counter.get_count() << std::endl;
++(++counter);
std::cout << counter.get_count() << std::endl;
输出:

2
4

你的原始代码是做什么的?

如果您尝试使用operator++的原始实现运行上述代码,它将打印以下内容:

2
3

这是因为你正在创建另一个你要返回的临时对象,当你写++(++counter)时,外部预增量将增加临时对象。因此,外部预增量不会改变counter.count的值。

即使你写++(++(++(++counter))),它也只相当于++counter

比较这里的输出:

  • http://www.ideone.com/xRXVq(原始代码)
  • http://www.ideone.com/xciWC(我的代码)

注意++(++counter)不调用未定义行为

最后一个函数是重载操作符。特别是前缀自增运算符。它允许您对该类的对象使用前缀++操作符。例如:

  Counter counter;
  ++counter;
  // note this is not implemented
  counter++;
这条线

  Counter(++count)

构造一个新的Counter对象,首先增加当前实例数,然后使用构造函数

   Counter(int c)
因此,前缀自增操作的结果是与调用前缀自增操作的实例不同的实例(递增副本)。