本文介绍了这个赋值运算符可以吗,复制ctor可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道这个赋值运算符和复制构造函数是否正常.我刚开始上课.在删除后将指针设置为NULL也是一种好习惯还是毫无意义.
#include <iostream> #include <string> using std::cout; using std::endl; using std::cin; class stickfigure { public: stickfigure(int j) : test(new int(j)) {} stickfigure(const stickfigure& ref) : test(new int(*ref.test)) {} stickfigure& operator = (const stickfigure& ref) { if (this != &ref) { delete test; test = new int(*ref.test); } return *this; } virtual ~stickfigure(){ delete test;} void print() const{cout << *test << endl;} private: int* test; }; int main(int argc, char** argv) { stickfigure stickone(76); stickone.print(); // copy stickfigure sticktwo(stickone); sticktwo.print(); // assignment stickfigure stickthree = sticktwo; stickthree.print(); }
解决方案
I was wondering if this assignment operator and copy constructor looks ok. I am just starting classes. also would it be good practice or pointless to set the pointer to NULL after delete.
#include <iostream> #include <string> using std::cout; using std::endl; using std::cin; class stickfigure { public: stickfigure(int j) : test(new int(j)) {} stickfigure(const stickfigure& ref) : test(new int(*ref.test)) {} stickfigure& operator = (const stickfigure& ref) { if (this != &ref) { delete test; test = new int(*ref.test); } return *this; } virtual ~stickfigure(){ delete test;} void print() const{cout << *test << endl;} private: int* test; }; int main(int argc, char** argv) { stickfigure stickone(76); stickone.print(); // copy stickfigure sticktwo(stickone); sticktwo.print(); // assignment stickfigure stickthree = sticktwo; stickthree.print(); }
解决方案
这篇关于这个赋值运算符可以吗,复制ctor可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!