注册 登录
编程论坛 C++教室

new的一个问题

jjg 发布于 2009-08-19 10:15, 510 次点击
程序代码:
class text
{
public:
       text(char* s)               //s是一个指针吗,str=new char[strlen(s)+1];中的s是指指向str字符串的指针?
       {
str=new char[strlen(s)+1];         //这里是不是动态分配,象一般是这样char* p=new char[],有什么区别?
strcpy(str,s);
len=strlen(s);
}   
...
void   main()
{
text array("good morning");
...
}
3 回复
#2
ly8610142009-08-19 10:38
回复 楼主 jjg

你的str是什么?
假设你的str是char*,
对第一个注释,假如有char* p;那么p既可以指向字符,也可以指向c风格字符串,如你main里的"good morning"
即char* p = "good morning";
对第二个注释,如果str是char*,那就是一个动态分配数组,没什么区别啊
#3
jjg2009-08-19 11:05
回复 2楼 ly861014

题目:
class text
{
public:
       text(char* s)                    
 {
str=new char[strlen(s)+1];        
strcpy(str,s);
len=strlen(s);
}     
char operator[](int n)
{
if(n>len-1)
{
cout<<"数组下标越界"<<endl;
return*(str+n);
}
void print(){
cout<<str<<endl;
}
private:
int len;
char* str;
};
void   main()
{
text array("good morning");
array.print();
cout<<"location 0:"<<array[0]<<endl;
cout<<"location 20:"<<array[20]<<endl;
}
#4
ly8610142009-08-19 11:10
回复 3楼 jjg

s不就是定义为char*吗,当然是个指针了。

char* str;
str = new char[strlen(s)+1];
和char* str = new char[strlen(s)+1]; 作用完全一样
1