林锐高质量编程中的几道面试题

内存的思考

片段1修改方法有三种:

方法一:可以在GetMemory函数中加上一个返回开辟空间的指针,通过它再对Test函数中的str指针重新赋值,可以解决这个问题。

方法二:由于Test中的str指针指向空,无法将指向空间的有效地址传递给GetMemory的形参,因此只需在Test函数中str指针指向一个非空的空间(不管空间大小多大),同样可以达到解决的效果。

方法三:就是下面的片段3

 

在C++ 程序中调用被C 编译器编译后的函数,为什么要加extern “C”?

        C++语言支持函数重载,C 语言不支持函数重载。函数被C++编译后在库中的名字与C 语言的不同。假设某个函数的原型为: void foo(int x, int y);该函数被C 编译器编译后在库中的名字为_foo,而C++编译器则会产生像_foo_int_int 之类的名字。C++提供了C 连接交换指定符号extern“C”来解决名字匹配问题。

编写strcpy 函数

char* strcpy(char* strDesc, const char* strSrc)
{
	assert( (strDesc!=NULL) && (strSrc!=NULL) );	//	确保二者有空间
	char* address = strDesc;
	while ( (*strDesc++=*strSrc++)!='\0' );

	return address;
}

strcpy的返回值的作用:为了实现链式表达式。

编写类String 的构造函数、析构函数和赋值函数

class String
{
public:
	String(const char* str = NULL);	//普通构造函数
	String(const String& other);	//拷贝构造函数
	~String(void);					//析构函数
	String& operator=(const String& other);	//赋值函数
private:
	char* m_data;
};
String::String(const char* str /* = NULL */)
{
	if(str==NULL)
	{
		m_data = new char[1];
		*m_data = '\0';
	}
	else
	{
		int length = strlen(str);
		m_data = new char[length+1];
		strcpy(m_data,str);
	}
}
String::String(const String &other)
{
	int length = strlen(other.m_data);
	m_data = new char[length+1];
	strcpy(m_data,other.m_data);
}
String::~String(void)
{
	delete[] m_data;
}
String& String::operator=(const String& other)
{
	//检查自赋值
	if( this == &other )
		return *this;

	//释放原有内存资源
	delete[] m_data;
	
	//分配新的内存资源,并复制内容
	int length = strlen(other.m_data);
	m_data = new char[length+1];
	strcpy(m_data,other.m_data);

	//返回本对象的引用
	return *this;
}



 

参考:来着林锐C/C++高质量编程

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值