Con trỏ và Nạp chồng toán tử

Trong đoạn code dưới đây khi chạy thì cho ra kết quả ở Box3 không đúng, khi không tạo destructor thì kết quả không có vấn đề. Cho em hỏi cách giải quyết trường hợp này nhưng vẫn giữ lại destructor và con trỏ ạ!

#include<iostream>
#include<string>
class Retangle
{
public:
	Retangle();
	~Retangle();
	Retangle(int, int, int);
	Retangle(const Retangle&);
	Retangle operator+ (const Retangle&);
	int Volume();
private:
	int width, lenght;
	int* height;
};

Retangle::Retangle() : width(10), lenght(10)
{
	height = new int;
	*height = 10;
	std::cout << "Default constructor: " << std::endl;
}

Retangle::~Retangle()
{
	delete height;
	std::cout << "*** Delete constructor ***" << std::endl;
};

Retangle::Retangle(int a, int b, int c) : width(a), lenght(b)
{
	height = new int;
	*height = c;
	std::cout << "Parameterized constructor initialized: " << std::endl;
}

Retangle::Retangle(const Retangle& parameter)
{
	width = parameter.width;
	lenght = parameter.lenght;
	height = new int;
	*height = *parameter.height;
}

Retangle Retangle::operator+ (const Retangle& p)
{
	Retangle temp;
	temp.width = width + p.width; 
	temp.lenght = lenght + p.lenght;
	*temp.height = *height + *p.height;
	return temp; 
}

int Retangle::Volume() { return width * lenght * (*height); }

int main()
{
	Retangle Box1;
	Retangle Box2(3, 4, 5);
	Retangle Box3;

	Box3 = Box1 + Box2;

	std::cout << "Volume of Box 1: " << Box1.Volume() << std::endl;
	std::cout << "Volume of Box 2: " << Box2.Volume() << std::endl;
	std::cout << "Volume of Box 3: " << Box3.Volume() << std::endl;

	system("pause");
	return 0;	
}

*Rectangle

Bạn chưa viết operator= :slight_smile:

1 Like

Cảm ơn bác rất nhiều!

83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?