|
发表于 2013-3-18 13:16:01
|
显示全部楼层
首先,程序有两处错误:
1、声明a的时候给的空间太小,hello12总共需要8个字节,只声明6个的话后面的12是没有地方存储的。
写或者读,都会报预先存储的提示:超出范围。
运行结果:
2、输出的时候需要输出a[i],直接对象是不可以的,编译不过去。
修改代码:
- #include<iostream>
- using namespace std;
- class A
- {
- public:
- A(int l){lenght = l; size = new char[lenght];}
- ~A(){delete []size;}
- int GetLength(){return lenght;}
- char&operator[](int i)
- {
- if(i>=0 && i<lenght)
- {
- return size[i];
- }
- else
- {
- cout<<"\n超出范围.";
- return size[lenght-1];
- }
- }
- private:
- int lenght;
- char *size;
- };
- int main()
- {
- A a(8);
- char *ch="hello12";
- for(int i=0;i<8;i++)
- {
- a[i]=ch[i];//a不是类对象吗;为什么这样可以这样赋值请详细说明,还有这条代码怎么调用运算符重载函的;
- }
- cout<<"\n\n";
- for(int i=0;i<8;i++)
- {
- //cout << i << endl;
- cout << a[i];
- //cout >> a; //cout<<a;//这条代码又是怎么调用 运算符重载函数的 ;
- }
- flushall();
- getchar();
- return 0;
- }
复制代码 运行结果:
|
|