私有拷贝构造函数

问题描述:

        私有拷贝构造函数的使用

问题解决:

#include <string.h>
#include<iostream>
using namespace std;

class noncopyable
{
private:
    noncopyable(const noncopyable& non) {}
    noncopyable& operator=(const noncopyable &)    {}
public:
    noncopyable(){}
    virtual ~noncopyable(){}
};


class Exception :public noncopyable
{
protected:
    char *message;
public:
    Exception(const char *msg)
    {
        message=new char[1024];
        strcpy(this->message,msg);    
        cout<<"error:"<<msg<<endl;
    }

    Exception(const string& msg)
    {
        message=new char[1024];
        strcpy(this->message,msg.c_str());
        cout<<"error:"<<msg.c_str()<<endl;
    }

    void printstack()
    {
        cout<<"error:"<<message<<endl;
    }

    ~Exception(){}
};

void  doexception(Exception e)
{

}

class Exception;

int main()
{
    Exception excp(string("song"));
    //doexception(excp);
    return 0;
}

注:

     如上所示的私有拷贝构造函数 noncopyable,Exception类public继承noncopyable(Exception类中noncopyable类private成员不可见),

在doexception函数中传递参数Exception对象,将调用Exception类的默认拷贝构造函数,默认拷贝构造函数将调用noncopyable中的

私有构造函数,私有成员调用不成功,因此实际使用doexception函数调用时提示如下错误:

错误    3    error C2248: “noncopyable::noncopyable”: 无法访问 private 成员(在“noncopyable”类中声明)
posted @ 2013-10-22 10:15  罗松超  阅读(1409)  评论(0编辑  收藏  举报