1 c++ inheritance pointers pointer-arithmetic
运行我的程序时,它会cout<<Core32->name()在第二次执行时终止.在研究了这个问题之后,我了解到在这种情况下指针算术会导致问题.还有,我也能够通过替代来解决该问题Core32++;与Core32+04;(真的不知道为什么这个工程).不过我的问题是为什么我能够调用方法Core32->procfun()而不是Core32->name().我查找对象切片,但它似乎没有解决我的问题.
编辑:想知道它为什么只能调用procfun()而不是name().这是旧考试的一个例子
#include <iostream>
#include<string>
using namespace std;
class Prozessor{
public:
virtual string name()=0;
};
class ARM : public Prozessor{
public:
virtual string name(){return "VAR";};
virtual int procbitw()=0;
string procfun(){return "VFP";};
};
class ARMv7:public ARM{
public:
int procbitw(){return 32;};
string procfun(){return "VFP";};
};
class ARMv8:public ARM{
public:
int procbitw(){return 64;};
string procfun(){return "VFP, NEON";};
};
int main()
{
const unsigned int n_cores=4;
ARM *HetQuadCore[n_cores]={new ARMv7, new ARMv7, new ARMv8, new ARMv8};
ARMv7* Core32=(ARMv7*)HetQuadCore[0];
for(int i =0;i<n_cores;i++)
{
cout<<Core32->procfun()<<endl;
cout<<Core32->name()<<endl;
cout<<"Bandwith is "<<HetQuadCore[i]->procbitw()<<endl;
Core32++;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你正在增加错误的东西.
你有一系列指针,对吧?而且你还有一个指向该数组中指针的指针.
您正在递增一个对象指针,而不是数组指针.
Array Hypothetical Objects Your pointer
"array pointer" (scattered) "Core32"
?
???????? «???? aPtr ????????? ?
? ptr1 ???????????????????????»? ARMv7 ?«???????????????
???????? ? ++aPtr ?????????
? ptr2 ?????????????????????????? ?????????
???????? ? ++aPtr ? ????????? ????»? ARMv8 ?
? ptr3 ???????????????????????? ??»? ARMv7 ? ? ?????????
???????? ? ++aPtr ? ????????? ?
? ptr4 ???????????????????????????????????????? ?????????
???????? ? ++aPtr ???????????????????»? ARMv8 ?
? … ? ?????????
????????
Run Code Online (Sandbox Code Playgroud)
因为这些对象[可能]散布Core32在一起,所以递增只会让你胡说八道.这永远不能保证工作.它只会在new调用给你动态分配的对象在内存中相邻时才会起作用.
您应该只使用i迭代数组,就像您已经做的那样,或者使用指针aPtr遍历数组的元素,然后再次取消引用以获取元素指向的对象.
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |