栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Java

c++类默认定义成员函数

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++类默认定义成员函数

c++类默认定义成员函数
  • 默认构造函数,如果没有定义
  • 默认析构函数,如果没有定义
  • 默认复制构造函数,如果没有定义
  • 默认赋值符号函数,如果没有定义
  • 默认取地址函数,如果没有定义。

默认复制构造函数与默认赋值符号函数的默认实现是将传入的对象的所有属性复制给当前对象。有时候会导致出问题。因此需要重写。

//.h文件,对类的属性与成员函数进行声明
class stringBad {
private:
	char* str;
	static int numLen;
public:
	stringBad();
	stringBad(const char* c);
	~stringBad();
	stringBad(const stringBad &);
	stringBad & operator=(const stringBad &);
};
//.cpp文件 对类中成员函数进行定义
int stringBad::numLen = 0;
stringBad::stringBad(const char * c) {
	int size = strlen(c);
	str = new char[size + 1];
	strcpy(str, c);
	numLen += 1;
}

stringBad::stringBad() {

}
stringBad::~stringBad() {
	cout << str << endl;
	numLen -= 1;
	delete[]str;
}
stringBad& stringBad::operator=(const stringBad& temp) {
	if (this == &temp)
		return *this;
	int size = strlen(temp.str);
	str = new char[size + 1];
	numLen += 1;
	strcpy(str, temp.str);
	return *this;
}
stringBad::stringBad(const stringBad& temp) {
	if (this == &temp)
		return;
	int size = strlen(temp.str);
	str = new char[size + 1];
	strcpy(str, temp.str);
	numLen += 1;
}

//主函数
int main(){
    stringBad str1("adads");
    //如果使用默认的复制构造函数,则将执行str2.str=str1.str,
    //两个对象的str指向同一地址,当str2执行析构函数时,str2.str内存会被delete,当st1在进行析构时就会报错
	stringBad str2(str1);
    stringBad str3("dadad");
    //原因同上
	stringBad str4 = str3;
}
转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/1041016.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号