Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OOP: Yêu cầu id là 1 thuộc tính: là 1 số nguyên có ... chữ số, tự động tăng? #8

Open
qnhat2004 opened this issue Jan 15, 2024 · 0 comments
Assignees

Comments

@qnhat2004
Copy link
Owner

qnhat2004 commented Jan 15, 2024

Với yêu cầu đề bài như thế này, ta có thể sử dụng 1 biến tĩnh để theo dõi số lượng đối tượng hiện tại, sau đó với mỗi lần nhập thêm 1 đối tượng ta có thể gán id của đối tượng hiện tại = số lượng đối tượng + id mặc định ban đầu.

VD: Nếu yêu cầu id là số nguyên có 5 chữ số -> id mặc định ban đầu là 10000

Ví dụ:

class Object
{
    static int numbers_of_obj;
    int id;
    friend istream& operator >> (Object &other)
    {
	other.id = 10000 + numbers_of_obj++;
	return in;
    }
};

int Object::numbers_of_obj = 0; // Khởi tạo số lượng đối tượng hiện tại bằng 0

int main()
{
    Object obj1; // id = 10000
    Object obj2; // id = 10001
}
@qnhat2004 qnhat2004 self-assigned this Jan 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant