请问:C++关于指向一个对象数组的指针的操作
请教:C++关于指向一个对象数组的指针的操作
代码如下:
#include <iostream.h>
class base
{
int a;
public:
int getvalue()
{
cout < < "base get " < <endl;
return a;
}
void setvalue(int temp)
{
cout < < "base set " < <endl;
a=temp;
}
};
class derived: public base
{
int b;
protected:
int getvaluef()
{
cout < < "derived get " < <endl;
return b;
}
void setvaluef(int temp)
{
cout < < "derived set " < <endl;
b = temp;
}
};
int main()
{
derived a[4];//1.这里的已经分配空间了吗?要new这个对象阿?
base* pbase= a;//2,这里是不能这么做,否则后面结构错误,pbase+1不知道指到哪里去了,怎么改正呢?
for(int i=0;i <4;i++)
{
a[i].setvalue(i+1);
}
for(i=0;i <4;i++)
{
cout < <pbase-> getvalue() < < ", ";
pbase++;
}
return 0;
}
提问在代码的注释里。help!!!!
------解决方案--------------------
1. 不需要 new 了,空间已经分配好,4个Derived
2. 这里没有错,pbase是个指针,开始直向了a的第一个元素,以后每次++一次就向后窜一个。
不过你这个程序结果不确定,setvalue是调用的Derived,getValue是调用的Based的,前一个设定b值,后一个打印a值。后面你会学到Virtual function,结果就不一样了。
------解决方案--------------------
代码如下:
#include <iostream.h>
class base
{
int a;
public:
int getvalue()
{
cout < < "base get " < <endl;
return a;
}
void setvalue(int temp)
{
cout < < "base set " < <endl;
a=temp;
}
};
class derived: public base
{
int b;
protected:
int getvaluef()
{
cout < < "derived get " < <endl;
return b;
}
void setvaluef(int temp)
{
cout < < "derived set " < <endl;
b = temp;
}
};
int main()
{
derived a[4];//1.这里的已经分配空间了吗?要new这个对象阿?
base* pbase= a;//2,这里是不能这么做,否则后面结构错误,pbase+1不知道指到哪里去了,怎么改正呢?
for(int i=0;i <4;i++)
{
a[i].setvalue(i+1);
}
for(i=0;i <4;i++)
{
cout < <pbase-> getvalue() < < ", ";
pbase++;
}
return 0;
}
提问在代码的注释里。help!!!!
------解决方案--------------------
1. 不需要 new 了,空间已经分配好,4个Derived
2. 这里没有错,pbase是个指针,开始直向了a的第一个元素,以后每次++一次就向后窜一个。
不过你这个程序结果不确定,setvalue是调用的Derived,getValue是调用的Based的,前一个设定b值,后一个打印a值。后面你会学到Virtual function,结果就不一样了。
------解决方案--------------------