C++基础学习DAY3-10 explicit关键字与new运算符

/*explicit关键字*/
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string.h>
using namespace std;
class MyString
{
public:
 MyString()
 {
  cout << "默认构造" << endl;
 }
 MyString(const char* str)
 {
  m_Str = (char*)malloc(strlen(str) + 1);
  strcpy(m_Str, str);
 }
 explicit MyString(int a)
 {
  m_Size = a;
 }
 MyString(const MyString & p)
 {
  m_Size = p.m_Size;
  m_Str = (char*)malloc(strlen(p.m_Str) + 1);
  strcpy(m_Str, p.m_Str);
  cout << "拷贝构造" << endl;
 }
 ~MyString()
 {
  if (m_Str != NULL)
  {
   free(m_Str);
   m_Str = NULL;
  }
  cout << "析构函数" << endl;
 }
 char* m_Str;
 int  m_Size;
};
void test01()
{
 MyString MyStr("GameLoL");
 MyString MyStr2(10);
 //MyString MyStr3 = 10;字符串为“10”?字符串长度为10?
 //隐式类型转换  相当于 MyString MyStr3 = MyString(10);
 //explict   禁止隐式类型转换
 cout << "m_Str :" << MyStr.m_Str << endl;
 cout << "m_Size:" << MyStr.m_Size << endl;
}
int main()
{
 test01();
 system("pause");
 return EXIT_SUCCESS;
}
/*new运算符*/
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string.h>
using namespace std;
class MyString
{
public:
 MyString()
 {
  cout << "默认构造" << endl;
 }
 ~MyString()
 {
  cout << "析构函数" << endl;
 }
 char* m_Str;
 int  m_Size;
};
void test01()
{
 //对象动态建立和释放  堆区开辟
 MyString* MyStr = new MyString;
 delete MyStr;
}
void test02()
{
 //通过new开辟数组 一定会调用默认构造函数  所以需要提供默认构造函数
 MyString* pArray = new MyString[10];
 //释放new出来的数组  delete []
    delete [] pArray;
}
int main()
{
 test02();
 system("pause");
 return EXIT_SUCCESS;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值