我是这里的 C++ 新手。我的任务是在不使用已经存在的 Vector 类的情况下创建一个 Vector 类。我不确定我是否正确实现了赋值运算符。如果是这样,我如何在主函数中使用它?
# include <iostream>
# include <string.h>
using namespace std;
class Vector{
public:
unsigned int * p;
size_t size;
Vector(){ // Default contructor
cout << "The default contructor" << endl;
this -> size = 20; // initial value
this -> p = new unsigned int [size];
// trying to set every elements value to 0.
for(int i = 0; i < size; i++){
*(p+i) = 0;
}
}
Vector (const Vector & v){ // The copy contructor
cout << "The copy constructor" << endl;
this -> size = v.size;
p = new unsigned int[size];
for(int i = 0; i < size; i++){
*(p+i) = *(v.p + i);
}
}
Vector& operator = (const Vector & v){
cout << "The assignment operator" << endl;
this -> size = v.size;
p = new unsigned int[size];
for(int i = 0; i < size; i++){
*(p + i) = *(v.p + i);
}
//p = p - size; // placing back the pointer to the first element
//return *this; // not sure here
}
void print_values(){
for(int i = 0; i< size; i++){
cout << *(p + i) << " ";
}
cout << endl;
}
};
int main(){
Vector * v1 = new Vector();
(*v1).print_values();
Vector * v2; // this should call the assignment operator but......... how?
v2 = v1;
(*v2).print_values();
Vector v3(*v1);
v3.print_values();
}