我一直在努力解决一些学校问题,并且我在operator>>
中关心内存分配,但看到了不同的解决方案,所以我在这里有点困惑。operator>>
当编译工作良好,提供良好的输出,但我不明白为什么,这里是代码.. (为什么我糊涂了是下面的代码)动态内存分配和输入(流)运算符C++
class Some
{
protected:
char *name;
int price;
int anything;
public:
Some(const char *name="", const int anything=0, const int price=0)
{
this->name=new char[strlen(name)+1];
strcpy(this->name, name);
this->anything = anything;
this->price=price;
}
~Some() { delete [] name; }
friend istream &operator>>(istream &in, Some &i)
{
return in>>i.name>>i.anything>>i.price;
}
void print(){
cout << name << " " << anything << " " << price;
}
};
主要
int main() {
// your code goes here
Some n;
cin >> n;
n.print();
return 0;
}
所以与Some n
我们做了一个对象,但是构造函数只分配了1个字符的内存,如果我错了,请纠正我的错误(并设置一些默认值)。之后,我们使用>> operator
输入Some
类型的对象,但只有一个字符分配给name
,我们可以输入尽可能多的数据。下面是带有一些输入Compiled Code的编译版本。我的思想在哪里错了?或者不应该这样做。谢谢 !!
诗篇,我们不允许使用这会照顾分配的库..
你的班级违反了三条规则。向char数组输入任意长度的数据是一个难题... – aschepler
你是对的。该代码(可怕)被破坏。 –
@aschepler是的我知道了,但这只是该课程的一部分,因为我不想将大块代码与我的问题联系在一起。 –