private:
int* a;
int* b;
public:
//default constructor:
Number() {
a = new int;
b = new int;
*a = 0;
*b = 0;
}
//constructor with arguments:
Number(int val1, int val2) {
a = new int;
b = new int;
*a = val1;
*b = val2;
}
//copy constructor:
Number(const Number& other) {
a = new int(*a = *(other.a));
b = new int(*b = *(other.b));
}
//getters and setters:
int getA() {
return *a;
}
int getB() {
return *b;
}
void setA(int val) {
*a = val;
}
void setB(int val) {
*b = val;
}
//method print:
void print() {
cout << "value of a: " << *a << " value of b: " << *b << endl;
}
}; 主要:
Number N1(2,3), N2;
N1.print(); //2-3
N2.print(); //0-0
N2 = N1;
N1.print(); //2-3
N2.print(); //2-3
N1.setA(12);
N1.print(); //12-3
N2.print(); //12-3 i want N2 to have 2-3 not 12-3 like N1,
//i want to separate N1 from N2
1条答案
按热度按时间bt1cpqcv1#
我是C++初学者,我有一个复制构造函数的问题,我需要做一个深复制,因为我的类有一个指针,我已经定义了一个复制构造函数,我也创建了一个对象N1(2,3),以及通过使用复制构造函数初始化的第二对象N2。复制构造函数不进行深复制,因为当我改变对象N1和N2的值时,他的值也改变了,我想用复制构造函数得到两个独立的对象
我的班级编号:
类别编号{
};
主要: