复制构造函数和重载的赋值运算符 [英] Copy Constructor AND Overloaded Assignment Operator
本文介绍了复制构造函数和重载的赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好..
希望你身体健康。好吧,我正在尝试更新运算符重载的概念,我在这里编写了一个简单的代码:
Hello guys..
Hope You Are At Good Sate Of Health. Well i'm trying to refresh the concept of operator overloading, I've written a simple code here:
#include <iostream>
using namespace std;
class Test
{
private:
int a;
int *b;
public:
Test();
Test(int x, int y);
void print();
Test(const Test& yourTest); // Copy Constructor -> const className(const className&)
const Test& operator=(const Test& anotherTest); // Assignment Operator -> const className &operator=(const className&)
~Test(); // Destructor
};
Test::Test()
{
a = -69;
b = new int;
}
Test::Test(int x, int y)
{
cout << "Constructor Called .. " << endl;
a = x;
b = new int(y);
//*b = y;
}
void Test::print()
{
cout << "A = " << a << "\t" << "B = " << b << "\n\n";
}
Test::Test(const Test& yourTest)
{
cout << "Copy Constructor Called .. " << endl;
a = yourTest.a;
b = new int;
*b = *(yourTest.b);
}
const Test& Test::operator=(const Test& anotherTest)
{
cout << "Assignment Operator Called .. " << endl;
if (this != &anotherTest){
a = anotherTest.a;
delete b;
*b = *(anotherTest.b);
return *this;
}
else
cout << "Self Assignment .. " << endl;
}
Test::~Test(){
delete b;
}
int main()
{
Test T1(2,3)
Test T2(T1);
T1.print();
T2.print();
return 0;
}
问题是,int * b的值是垃圾,请你帮我识别错误.. ??!
我敏锐地等你回复..
The issue is, the value of int *b is garbage, could you please help me to identify the mistake .. ??!
I keenly waiting You Reply ..
推荐答案
你应该打印
* b
而不是b
,在Test :: print $ c $中c>功能。
另一个问题:您应该从中删除
。您不必删除内存,只需为其分配一个新值。删除b;
行运算符=
Another issue: You should remove the delete b;
line from operator=
. You don't have to delete the memory, just assign a new value to it.
#include <conio.h>
#include <iostream>
using namespace std;
class Test
{
private:
int a;
int *b;
public:
Test();
Test(int x, int y);
void print();
Test(const Test& yourTest); // Copy Constructor -> const className(const className&)
const Test& operator=(const Test& anotherTest); // Assignment Operator -> const className &operator=(const className&)
~Test(); // Destructor
};
Test::Test()
{
a = -69;
b = new int;
*b=0;
}
Test::Test(int x, int y)
{
cout << "Constructor Called .. " << endl;
a = x;
b = new int;
*b = y;
}
void Test::print()
{
cout << "A = " << a << "\t" << "B = " << *b << "\n\n";
}
Test::Test(const Test& yourTest)
{
cout << "Copy Constructor Called .. " << endl;
a = yourTest.a;
b = new int;
*b = *(yourTest.b);
}
const Test& Test::operator=(const Test& anotherTest)
{
cout << "Assignment Operator Called .. " << endl;
if (this != &anotherTest){
a = anotherTest.a;
//delete b;
*b = *(anotherTest.b);
return *this;
}
else
{
cout << "Self Assignment .. " << endl;
return *this;
}
}
Test::~Test(){
delete b;
}
int main()
{
Test T1(2,3);
Test T2(T1);
T1.print();
T2.print();
getch();
return 0;
}
这篇关于复制构造函数和重载的赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文