c++ - 填充指向返回结构的类获取函数的指针数组
问题描述
我正在尝试填充指针数组。我需要 MyClass 的两个(或更多)实例的 myVar 数据。但由于某种原因,我没有得到我想要的结果。
头文件:
typedef struct {
int value;
int otherValue; // We do nothing with otherValue in this example.
} mytype_t;
class MyClass {
public:
MyClass(void) {}
~MyClass(void) {}
void set(float _value) {
myVar.value = _value;
}
mytype_t get(void) { // We get the data through this function.
return myVar;
}
protected:
private:
mytype_t myVar; // Data is stored here.
};
cp文件:
MyClass myInstances[2];
int main(void) {
// Set private member data:
myInstances[0].set(75);
myInstances[1].set(86);
mytype_t *ptr[2];
ptr[0] = &(myInstances[0].get());
ptr[1] = &(myInstances[1].get());
Serial.print(ptr[0]->value); // Prints 75 -> As expected!
Serial.print(":");
Serial.print(ptr[1]->value); // Prints 86
Serial.print("\t");
for (int i = 0; i < 2; i++) {
Serial.print(myInstances[i].get().value); // Prints 75, and next iteration 86 -> As expected.
if (i == 0) Serial.print(":");
ptr[i] = &(myInstances[i].get()); // Set ptr
}
Serial.print("\t");
Serial.print(ptr[0]->value); // Prints 86 -> Why not 75..?
Serial.print(":");
Serial.print(ptr[1]->value); // Prints 86
Serial.println();
}
程序输出:
75:86 75:86 86:86
并不是:
75:86 75:86 75:86
为什么它指向另一个实例(值为 86)呢?我该如何解决?还是我想要的东西不可能?
PS 代码在PC平台上运行。我正在使用我自己的基于 Arduino 语法的 Serial 类。
解决方案
您正在分配指向从返回的临时对象的指针get
。您没有分配指向MyClass
对象内部的指针。更改您的代码,以便get
返回引用而不是副本。
mytype_t& get(void) { // We get the data through this function.
return myVar;
}
那应该使您的程序正常工作。但是,返回对另一个对象内部的引用并不是一种好的做法。您可能应该重新考虑您的设计。
推荐阅读
- html - 引导模式:显示错误的内容
- reactjs - 如何在日期选择器和输入框上有不同的日期?
- r - 你如何合并数字列?
- java - 在原位链表上实现自然归并排序,并且只交换来自节点的项目
- xamarin.forms - xamarin表单列表视图中的水平列表视图
- python - 上一列中找到的列表值的新熊猫列
- python - 使用 Seaborn 的散点图
- powershell - 使用 Powershell Taskkill 过滤您不想被杀死的多个进程的语法是什么?
- python - 有没有办法将浮点变量添加到现有的平行?
- google-maps - 为什么我不能使用此代码在 Google 地图上设置缩放级别?