如何在方法中更改受方法影响的变量/java put方法的c++替代方案
How to change the variable, affected by a method, in the method?/c++ alternative to java put method
我希望该方法通过在代码中包含变量来更改变量。与java中的put方法类似,我希望通过将索引设置为一个数字,然后用另一个数字重写该索引处的数字来影响变量。
例如:
#include <iostream>
#include <string>
using namespace std;
string put(int pos, float f)
{
a = f[pos];
//pos - The index at which the float will be written
//f - The float value to be written
}
int main ()
{
int x = 6;
int y = 2;
int z = 3;
float a[100];
a.put(10, y)
}
唯一的问题是,put方法只更改变量a
,而我希望它更改指向它的任何变量。因此,如果有一个像b
这样的变量,并且在代码中出现为b.put(23, z)
,它会用数字3重写索引23处的任何内容。
似乎C++中的指针可以实现您所尝试的。
void put(float* a, int pos, float change){
a[pos]=change;
}
当然,您需要小心访问超过数组大小的内存位置,但此put函数适用于任何数组。然而,这就引出了一个问题,即您到底想做什么,因为直接更改值会更容易阅读。我能想象你在Java中引用的唯一一个"put"方法是HashMaps,而C++的等效方法是unordered_map。更多信息可以在这里找到。它有一个插入函数,相当于Java put。
通过阅读上面的评论,使用指向变量的指针而不是变量本身将实现您想要的目标。
定义类来创建此类函数。
#include <iostream>
#include <string>
class hoge {
private: // only for readability
float a[100];
public:
void put(int pos, float f)
{
if (pos >= 0 && pos < (int)(sizeof(a) / sizeof(a[0]))) a[pos] = f;
//pos - The index at which the float will be written
//f - The float value to be written
}
};
int main ()
{
int x = 6;
int y = 2;
int z = 3;
hoge a;
a.put(10, y);
}
相关文章:
- 私有变量无法正常工作的C++getter方法(只有Java经验)
- Android:使用 c++ 中的 byte[] 参数调用 java 方法
- 使用本机 JNI 静态方法实现C++ Java 运行时错误
- 如何在JNI中从线程内部调用JAVA方法
- Java(或C++)如何处理接口中定义的方法的调用
- 如何调用传递给 JNI 'jobject' 的 Java 对象的子类/子类的方法
- Qt 调用具有 1 个以上参数的 java 方法
- Java 调用 dll 字符串返回类型方法
- 从 Java 类调用C++方法?
- Android 无法从本机代码调用 Java 方法 JNI
- 是否可以在SO库中公开C API以访问Android JAVA方法
- 将 OpenCV 方法从 Java 重写为 C++
- 如何从 NDK(JNI) 调用特定的 Java 方法
- 在 C++ vs Java 中从构造函数调用被覆盖的方法
- C/C++ 函数/方法与 Java 的公开
- C++方法与Java的比较(从Java到C ++的语法)
- C 多线程JAVA JNI方法调用
- Java加载DLL,该DLL从JNI中的另一个DLL导出方法
- 如何从 JAVA 程序中访问文件中定义的类.DLL方法
- 从 JNI 调用 getWritableDatabase (SQLCipher java 方法)