我是这里的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();
}
最佳答案
您的电话:
v2 = v1;
不会致电您的赋值运算符。它只是将一个指针分配给另一指针。您需要在对象之间进行分配,以供操作员使用。
您想要类似的东西:
Vector v1;
v1.print_values();
Vector v2;
v2 = v1;
等等。您的程序也有一些内存泄漏-注意!
编者注:为什么用
*(p+i)
代替p[i]
?后者更容易阅读。关于c++ - 这应该调用赋值运算符,但是如何?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19012185/