我正在尝试实现自己的CString类。我在浅层复制指针时遇到了一些问题。 这是班级
override func viewDidLoad() {
super.viewDidLoad()
let nibFile : UINib = UINib(nibName: "DescriptionNearCollectionViewCell", bundle: nil)
descriptionCollectionView.register(nibFile, forCellWithReuseIdentifier: "descriptionCell")
let nibFile2 : UINib = UINib(nibName: "DescriptionImageSliderCollectionViewCell", bundle: nil)
descriptionCollectionView.register(nibFile2, forCellWithReuseIdentifier: "descriptionCell")
// Do any additional setup after loading the view.
}
这是main():
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "descriptionCell", for: indexPath)
return cell
}
问题在于浅层复制发生;我知道写作
#include<iostream>
#include<string.h>
using namespace std;
class myCString{
public:
myCString(){
m_value = NULL;
}
myCString(char* strParam){
int len = length(strParam);
m_value = new char[len+1];
for(int i=0;i<len; i++)
{
m_value[i] = strParam[i];
}
m_value[len]='\0';
}
myCString(const myCString& obj)
{
int len = obj.length();
m_value = new char[len+1];
for(int i=0;i<len; i++)
{
m_value[i] = obj.m_value[i];
}
m_value[len]='\0';
}
myCString(const myCString *obj)
{
int len = obj->length();
m_value = new char[len+1];
for(int i=0;i<len; i++)
{
m_value[i] = obj->m_value[i];
}
m_value[len]='\0';
}
const int length() const
{
return length(m_value);
}
myCString operator=(myCString obj)
{
int i=0;
int length= obj.length();
m_value = new char[length + 1];
for(;i<obj.length(); i++)
{
m_value[i] = obj.m_value[i];
}
m_value[length]='\0';
return m_value;
}
~myCString()
{
delete []m_value;
m_value = NULL;
}
friend ostream& operator<<(ostream& os, const myCString obj);
private:
const int length(char* strParam)const
{
int i=0;
while(strParam[i]!='\0'){
i++;
}
return i;
}
char *m_value;
};
ostream& operator<<(ostream& os, myCString obj)
{
os<<obj.m_value;
return os;
}
将解决问题;但我想保持主要功能完整,并在课堂上进行一些更改。 无论如何我能做到吗? 提前谢谢。
答案 0 :(得分:0)
改变你的 <{1}}签名
myCString(char* strParam)
答案 1 :(得分:0)
您的请求是在myCString *ptr2 = ptr
行中制作一份objekt的深层副本,
但是这个目标是通过对象的类编程无法达到的,因为这一行只复制指针而不涉及对象的类。
如果你想调用复制构造函数,你必须按照你的建议编写:
myCString *ptr2 = new myCString(ptr)
;
或者你可以写:
myCString mystr("Hi! This is myCString\n");
cout<<mystr;
myCString mystr2 =mystr;
cout<<mystr;
另一个问题:调用函数ostream& operator<<(ostream& os, myCString obj)
为参数obj调用复制操作符myCString(const myCString& obj)
。你应该写
ostream& operator<<(ostream& os, const myCString& obj)
避免这种情况。