[英]C++ copy constructor, destructor error and more
I am really new to C++. 我真的是C ++新手。 I have tried to figure out how copy constructor works and also destructor, but I cant get it to work just wright.
我试图弄清楚复制构造函数和析构函数是如何工作的,但是我无法让它正常工作。
I get two errors: 我得到两个错误:
error: expected primary-expression before ';' 错误:“;”之前的预期主表达式 token
代币
delete []; 删除[];
class DynamicLine has no member named 'p2', DynamicLine类没有名为“ p2”的成员,
This is my header file: 这是我的头文件:
template<class T>
class DLine {
public:
DLine (T *v1, T *v2)
: v1 {v1},
v2 {v2}
{}
T* v1;
T* v2;
// Copy constructor
DLine(const DLine &l)
{
v1 = l.v1;
v2 = l.v2;
}
DLine& operator= (const DLine &l) {
if (this == &l) {
return *this;
}
v1 = l.v1;
v2 = l.v2;
return *this;
}
~DLine()
{
delete [];
}
};
I also have a vector class: 我也有一个向量类:
using namespace std;
Vector2::Vector2(float nx, float ny)
: x {nx}
, y {ny}
{
}
float Vector2::distanceFrom(Vector2 v) {
return sqrt( (x - v.x)*(x - v.x) + (y - v.y)*(y - v.y) );
}
ostream& operator << (ostream& os, Vector2 v) {
return os << "(" << v.x << "," << v.y << ")";
}
And this is part of my test program: 这是我的测试程序的一部分:
Vector2 p1 {3.0, 5.0};
Vector2 p2 {0,0};
Vector2 p3 {7.0, 8.0};
DLine<Vector2> l1 {&p1, &p2};
DLine<Vector2> l2 {nullptr, nullptr};
l2 = l1;
l2.p2 = &p3;
p1.x = 2.0;
You are not dynamically allocating memory... what are you trying to delete then... 您不是在动态分配内存...您要删除的内容然后...
You need not to delete all the pointers.... delete
operator is used to delete memory allocated using through new
operator. 您不需要删除所有指针。...
delete
运算符用于删除通过new
运算符分配的内存。
So here you can remove delete
statement from destructor.. 因此,在这里您可以从析构函数中删除
delete
语句。
At least you use incorrectly operator delete[]
(see http://www.cplusplus.com/reference/new/operator%20delete%5B%5D/ ): 至少您错误地使用了运算符
delete[]
(请参阅http://www.cplusplus.com/reference/new/operator%20delete%5B%5D/ ):
pt = new MyClass[3];
delete[] pt;
delete
is used to release the memory that's dynamically allocated. delete
用于释放动态分配的内存。 v1
and v2
are the members of the class Dline
and p2
is just a variable you declared in the program. v1
和v2
是Dline
类的成员,而p2
只是您在程序中声明的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.