简体   繁体   中英

C++ copy constructor, destructor error and more

I am really new to 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 [];

  1. I have tried to put different things after delete [] but none of them worked, so I left it just blank at the moment.

class DynamicLine has no member named 'p2',

  1. What am I doing wrong? I did decleare p2 in my test program.

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.

So here you can remove delete statement from destructor..

At least you use incorrectly operator delete[] (see http://www.cplusplus.com/reference/new/operator%20delete%5B%5D/ ):

pt = new MyClass[3];
delete[] pt;
  1. delete is used to release the memory that's dynamically allocated.
  2. v1 and v2 are the members of the class Dline and p2 is just a variable you declared in the program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM