首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

拷贝构造函数相关有关问题,求高手解答

2012-09-10 
拷贝构造函数相关问题,求高手解答!已知程序使用类提供默认拷贝构造函数存在隐患:类声明如下:C/C++ code#if

拷贝构造函数相关问题,求高手解答!
已知程序使用类提供默认拷贝构造函数存在隐患:
类声明如下:

C/C++ code
#ifndef UNIT1_H_#define UNIT1_H_#include <iostream>#include <string>using namespace std;class StringBad{private:    char *str;    int len;    static int num_string;public:    StringBad();    StringBad(const char *s);    ~StringBad();    friend ostream & operator <<(ostream &os, const StringBad &t);};#endif

主函数:
C/C++ code
#include "unit1.h"void callme1(StringBad &t);void callme2(StringBad t);int main(){    StringBad headline1("a");    StringBad headline2("b");    cout << "headline1: " << headline1 << endl;    cout << "headline2: " << headline2 << endl;    StringBad dl = headline1;//调用拷贝构造函数是否生成临时对象?程序执行结束后调用析构函数释放dl    callme2(headline1);//调用拷贝构造函数生成临时对象并在函数执行结束后析构临时对象;    return 0;}void callme1(StringBad &t){    cout << "referenece: " << endl;    cout << t << endl;}void callme2(StringBad t){    cout << "value: " << endl;    cout << t << endl;}

问题:调用拷贝构造函数是否生成临时对象?

[解决办法]
StringBad dl = headline1;//调用拷贝构造函数是否生成临时对象?程序执行结束后调用析构函数释放dl

不会生成临时对象,这里只涉及了对象 dl 和 对象headline1 的一个浅拷贝的过程,及讲headline1中的所有变量拷贝到dl中的变量。
把分给我吧,我还可以给你说的详细点。

热点排行