c++ - 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。
感谢帮助!
解决方案
Tab& Tab::set(int, int, double) {
// whatever
return *this;
}
此处的返回类型是Tab&
为了使后续调用将应用于Tab
对象。Returning*this
返回对当前对象的引用,因此第二次set
调用将更改与第一次调用相同的对象set
。
推荐阅读
- swift - 如何在 Mac 而不是 iPhone 上创建和打印屏幕外 SwiftUI 视图
- javascript - 如何获取浏览器视口的小数宽度和高度?
- c# - ASP.NET Core Razor 页面绑定属性并在模型中保留数据
- intellij-idea - IntelliJ IDEA 控制台似乎在行之间有额外的“填充”,导致背景颜色高于实际行高
- javascript - 无法读取未定义的属性“库存”
- typescript - Vue + Typescript + 汇总
- python - 如何在 Python 中结合 groupby、rolling 和多列的创建
- php - 无法猜测 MIME 类型,因为没有可用的猜测器(您是否启用了 php_fileinfo 扩展?)。莱维尔 8
- excel - VBA:非连续范围 - 对象不支持此属性或方法
- scala - 错误:“数据源 org.apache.spark.sql.cassandra 不支持流式读取”