源码1 禁用拷贝构造函数 重载=运算符,以禁用=赋值 字符串拆分

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<dirent.h>
#include<errno.h>
#include<string>
#include<iostream>
#include<cstring>
using namespace std;

class sampleClass {
  public:
    sampleClass(int size);
    virtual ~sampleClass();
    int getSize() {return mSize;}
    char* getBuffer() {return mpBuffer;}
  //public:
  private:
    // 禁用拷贝构造函数
    sampleClass(const sampleClass& instance);
    // 重载=运算符,以禁用=赋值
    sampleClass& operator=(const sampleClass& instance);
    
  private:
    int mSize;
    char* mpBuffer;  
};    

sampleClass::sampleClass(int size) :
  mSize(size),
  mpBuffer(NULL) {
    if (size > 0) {
        mpBuffer = new char[size];
        if (mpBuffer)
            memset(mpBuffer, 0, size);
    }
    cout<<__FUNCTION__<<","<<__LINE__<<endl;
}

sampleClass::~sampleClass() {
    if (mpBuffer) {
        delete mpBuffer;
        mpBuffer = NULL;
    }
    cout<<__FUNCTION__<<","<<__LINE__<<endl;
}



sampleClass::sampleClass(const sampleClass& instance) {
    cout<<__FUNCTION__<<","<<__LINE__<<endl;
    sampleClass* pInstance = const_cast<sampleClass*>(&instance);
    if (NULL == pInstance)
        return;
    mSize = pInstance->getSize();
    if (mSize > 0) {
        mpBuffer = new char[mSize];
        if (mpBuffer)
            memset(mpBuffer, 0, mSize);
    }
}

sampleClass& sampleClass::operator=(const sampleClass& instance) {
    cout<<__FUNCTION__<<","<<__LINE__<<endl;
    sampleClass* pInstance = const_cast<sampleClass*>(&instance);
    cout <<this<<"=?"<<pInstance<<endl;
    if (NULL != pInstance && this != pInstance) {
        mSize = pInstance->getSize();
        if (mSize > 0)
            mpBuffer = new char[mSize];
        if (mpBuffer) {
            memset(mpBuffer, 0, mSize);
            char* pBuff = pInstance->getBuffer();
            if (pBuff)
                memcpy(mpBuffer, pBuff, mSize);
        }
    }
    return *this;
}

int main()
{
#if 1
    sampleClass instance1(1);
    //sampleClass instance2(instance1);
    sampleClass instance3(3);
    //instance3 = instance1;
#else
    // 字符串拆分示例 
    std::string source("0.513 0.618 0.324 0.465 -0.453 ");
    double a[5] = {0.0};
    std::size_t pos = 0;
    std::string curStr;
    int cout = 0;
    do {
        pos = source.find_first_of(" ");
        if (string::npos == pos)
            break;
        curStr = source.substr(0, pos);
        a[cout++] = atof(curStr.c_str());
        source = source.substr(pos+1, source.length() - curStr.length() - 1);
    } while (true);

    for (int i=0; i<cout; i++) {
        printf("%lf ", a[i]);
    }
    printf("\n");
#endif    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值