首页 > 解决方案 > C++ 类返回自身

问题描述

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

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();

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

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

感谢帮助!

标签: c++pointersmethods

解决方案


Tab& Tab::set(int, int, double) {
    // whatever
    return *this;
}

此处的返回类型是Tab&为了使后续调用将应用于Tab对象。Returning*this返回对当前对象的引用,因此第二次set调用将更改与第一次调用相同的对象set


推荐阅读