01/10/2018, 13:36
Copy constructor và constructor có phải cũng chính là 1 kiểu dạng của overload?
Mọi người cho mình hỏi copy constructor và constructor cũng chính là 1 kiểu dạng của overload đúng ko ạ ?
VD
#include <iostream>
class Line
{
public:
int getLength(void);
Line(int len);
Line(const Line &obj);
~Line();
private:
int* ptr;
};
Line::Line(int len) :ptr(new int)
{
std::cout << "Simple Constructor has been create" << std::endl;
*ptr = len;
}
Line::Line(const Line &obj) :ptr(new int)
{
*ptr = *obj.ptr;
}
Line::~Line()
{
std::cout << "Freeing memory!" << std::endl;
delete ptr;
}
int Line::getLength() {
return *ptr;
}
void display(Line obj) {
std::cout << "Length of line: " << obj.getLength() << std::endl;
}
int main() {
Line _line(10);
Line _line2(_line); // Ở trong _line2, _line sẽ chọn cho mình member thích hợp -> copy constructor
display(_line);
display(_line2);
system("pause");
return 0;
}
Bài liên quan
Đúng vậy. Các overload thực chất vẫn có tên riêng sau khi biên dịch