文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>深度复制

深度复制

时间:2011-05-17  来源:hailong

找了个代码,但不知道问题在哪?

博文链接http://www.cnitblog.com/qingchunjun/archive/2006/12/28/21212.html

“今天在学习c++的深度复制概念时,发现c++中的字符数组和字符指针两种形式的数据进行深度复制时,有一些小小的差异,本人初学,特记之,以防遗忘。
在 c++中,当一个字符串以字符数组的形式定义时,都具有数组长度的定义,以char str[30]为例。这时代表系统已经分配了30个字节的内存给该变量,所以在执行深度复制时,一般采用strncpy函数进行复制,而不用new的形式 分配新的内存。而当一个字符串是以字符指针的形式定义时,则代表该变量将在程序执行时才给予分配内存,这种形式的变量在执行深度复制时,一般需要根据 strlen函数确定的字节数大小来new一个新的内存给这个指针,然后再利用strcpy进行字符串的复制,这就是所谓的动态分配内存。举例说明如下 (代码在borland C++6.0下调试通过):”

#include <iostream>
using namespace std;
class example{
private:
        enum{SIZE=30};
        char str[SIZE];
        char *cp;
public:
        example(){str[0]='\0';cp=NULL;}
        example(const char *,const char *);
        example(const example &);
        ~example();
        void show() const;
};


example::example(const char *s,const char *p){
        std::strncpy(str,s,SIZE-1);
        str[SIZE]='\0';
        cp=new char[std::strlen(p)+1];
        strcpy(cp,p);
}
example::example(const example &e){
        std::strncpy(str,e.str,SIZE-1);
        str[SIZE]='\0';
        cp=new char[std::strlen(e.cp)+1];
        strcpy(cp,e.cp);
}
example::~example(){delete []str;}
void example::show() const{
        std::cout << str <<std::endl;
        std::cout << cp <<std::endl;
}

int main(){
        example e1("ok","good");
        example e2(e1);
        e1.show();
        e2.show();
        std::cin.get();
        return 0;
}

相关阅读 更多 +
排行榜 更多 +
瓢虫少女

瓢虫少女

飞行射击 下载
潜艇鱼雷

潜艇鱼雷

飞行射击 下载
网络掠夺者

网络掠夺者

飞行射击 下载