#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
}
源码1 禁用拷贝构造函数 重载=运算符,以禁用=赋值 字符串拆分
最新推荐文章于 2022-07-26 16:32:02 发布