【问题标题】:C++ class returns itselfC++ 类返回自身
【发布时间】:2018-11-09 17:18:01
【问题描述】:

我需要创建一个提供二维数组操作方法的类。这对我来说不是问题,但我很难创建一个返回自己的对象的方法。

Tab t(7,7,0.1);//this creates class with 7x7 array filed with 0.1 - it works perfectly
t.print(); //prints array 0 - this also works
t.set(6,6,7.5f).set(6,5,8.6f); //should set 7.5 on pos[6][6] and 8.6 on pos [6][5]
t.print();

我不知道这个方法“set”应该返回什么。我不太了解c++的语法,因为我习惯了java。我看到它应该返回指向 this 的指针,或者指针 this (&this) 的内容,或者可能是常量指针?我不知道。

而且我不想使用 c++11。

感谢您的帮助!

【问题讨论】:

  • 返回*this作为参考?
  • 它根本不应该返回一个指针。你不能在指针上使用.。
  • 我真的不清楚为什么人们对这个问题投了反对票。真的!
  • @MikeDinescu 好吧,不完整的示例代码(没有 MCVE),没有显示任何研究,很可能是一个骗局,这些理由对你来说足够了吗?
  • 重新打开。 “重复”是关于语法错误,而不是关于支持链接的返回类型应该是什么。

标签: c++ pointers methods


【解决方案1】:
Tab& Tab::set(int, int, double) {
    // whatever
    return *this;
}

这里的返回类型是Tab&,以便后续调用将应用于Tab 对象。返回*this 会返回对当前对象的引用,因此第二个set 调用将更改与第一个set 调用相同的对象。

【讨论】:

    【解决方案2】:
    class Foo {
    public:
        int x_;
    
        Foo() : x_(0) {}
        Foo( int x ) : x_(x) {}
    
        Foo operator()() { return *this; }
    }
    
    int main() {
        Foo a( 3 );
        Foo b = a();
    
        std::cout << b << '\n';
    
        return 0;
    }
    

    输出

    3
    

    【讨论】:

      猜你喜欢
      • 2019-02-09
      • 1970-01-01
      • 2023-02-19
      • 1970-01-01
      • 1970-01-01
      • 2019-08-26
      • 1970-01-01
      • 1970-01-01
      • 2013-07-06
      相关资源
      最近更新 更多