我用C ++编写了该程序,如果在注释中加上最后两行,则可以很好地工作:a = b;
MyAr c(b);
我使用删除它的方法对其进行了测试。问题在于我认为的*this
指针,当我编译并运行时,程序会闪烁一会儿然后消失。你能帮我么?谢谢!
#include <iostream>
using namespace std;
class MyAr {
int *p;
int len;
public:
MyAr();
MyAr(int a);
MyAr(const MyAr& ob);
~MyAr();
MyAr& operator=(const MyAr& ox) { *this = ox; }
int& operator[](int i) { return p[i]; }
int length();
};
MyAr::MyAr() : p(0), len(0) {}
MyAr::MyAr(int a) : p(new int[a]), len(a) {}
MyAr::MyAr(const MyAr& ob) { *this = ob; }
MyAr::~MyAr() { delete p; }
int MyAr:: length(){
return len;
}
int main(){
MyAr a;
MyAr b(10);
for(int i=0; i< b.length(); ++i)
b[i] = i;
a = b;
MyAr c(b);
system("pause");
return(0);
}
最佳答案
您将在c ++中做过的最重要的事情之一就是学会编写正确的构造函数和析构函数:
#include <cassert>
#include <cstring>
#include <utility>
class MyAr {
int *p;
int len;
public:
MyAr() : p(nullptr), len(0) {};
MyAr(int a) : p(new int[a]), len(a) {};
// because we are overloading the destructor, rule of 3 is required (c++03)
MyAr(const MyAr& ob)
: p( nullptr), len(ob.len)
{
if (len) {
assert(ob.p);
p = new int[len];
std::memcpy(p, ob.p, len);
}
}
MyAr& operator=(const MyAr& r)
{
MyAr tmp(r);
swap(tmp);
return *this;
}
~MyAr() {
// note: delete []
delete [] p;
}
// or rule of 5 (c++11)
#if __cplusplus >= 201103L
MyAr(MyAr&& r)
: p(r.p)
, len(r.len)
{
r.p = nullptr;
r.len = 0;
}
MyAr& operator=(MyAr&& r)
{
auto tmp = MyAr(std::move(r));
swap(tmp);
return *this;
}
#endif
void swap(MyAr& other)
{
using std::swap;
swap(p, other.p);
swap(len, other.len);
}
int& operator[](int i) { return p[i]; }
int length();
};