Scribbling

[C++] Interface 본문

Computer Science/C++

[C++] Interface

focalpoint 2024. 10. 2. 02:46
#include <iostream>


using namespace std;

class Printable {
	friend ostream& operator<<(ostream& os, const Printable& obj);
public:
	virtual void print(ostream& os) const = 0;
	virtual ~Printable() {}
};

ostream& operator<<(ostream& os, const Printable& obj) {
	obj.print(os);
	return os;
}

class class1 : public Printable {
public:
	virtual void print(ostream& os) const override {
		os << "class1" << endl;
	}
};

class class2 : public Printable {
public:
	virtual void print(ostream& os) const override {
		os << "class2" << endl;
	}
};

int main() {
	class1 cls1;
	class2 cls2;
	cout << cls1 << endl;
	cout << cls2 << endl;
}

'Computer Science > C++' 카테고리의 다른 글

[C++] LRU Cache  (2) 2024.10.05
[C++] Object Oriented Programming  (0) 2024.10.01
[C++] Strings  (0) 2024.09.30
[C++] Abstract Class, Polymorphism  (0) 2024.09.28
[C++] Virtual Functions  (0) 2024.09.28