【发布时间】:2015-10-21 19:52:29
【问题描述】:
对象(非动态)是内存中的数据块。
有没有办法循环打印对象中的每个项目?
我尝试使用“this”来执行此操作,但我不断收到错误。
#include "stdafx.h"
#include <iostream>
#include "TestProject.h"
using namespace std;
class myclass {
int someint = 10;
double somedouble = 80000;
int somearray[5] = {0, 1, 2, 3, 4};
public:
void somefunction();
};
void myclass::somefunction() {
cout << "\n test \n" << this;
myclass *somepointer;
somepointer = this;
somepointer += 1;
cout << "\n test2 \n" << *somepointer;
//Error: no opperator '<<' matches these operands
}
int main() {
myclass myobject;
myobject.somefunction();
return 0;
}
我猜这个错误是因为类型不匹配。但我真的想不出解决办法。是否有动态类型,或者我必须以某种方式测试类型?
【问题讨论】:
-
除非您的类完全由指针组成,否则以 1 遍历内存不太可能将您带到下一个对象。
-
另外...你得到“错误:没有运算符 '
-
实际上,指针比
char大,所以它甚至不能只使用指针。你只需要char -
我也会看看这个stackoverflow.com/questions/15430848/… 你保证“按照声明的顺序增加地址”。但是有很多你不能保证你的课堂记忆。
-
这个想法是循环运行它。
标签: c++ this pointer-arithmetic this-pointer