zoukankan      html  css  js  c++  java
  • 私有拷贝构造函数

    问题描述:

            私有拷贝构造函数的使用

    问题解决:

    #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”类中声明)
  • 相关阅读:
    shell入门-cut命令
    shell入门-特殊符号
    shell入门-系统和用户的配置文件
    shell入门-变量
    shell入门-shell特性
    linux命令-yum工具详解
    linux命令-rpm查询包
    linux命令-rpm安装和卸载
    math 数学模块
    random 随机模块
  • 原文地址:https://www.cnblogs.com/luosongchao/p/3381933.html
Copyright © 2011-2022 走看看