#include<iostream> using namespace std; class Base { public: virtual void f() { cout << "Base" << endl; } }; class D1 : public Base { void f() { cout << "D1" << endl; } }; class D2 : public Base { void f() { cout << "D2" << endl; } }; void pointer(Base *b) { b->f(); } void reference(Base &b) { b.f(); } void base(Base b) { b.f(); } #define test_pointer(x) cout << "pointer " #x << ": "; pointer(x); #define test_reference(x) cout << "reference " #x << ": "; reference(x); #define test_base(x) cout << "base " #x << ": "; base(x); void test_objects() { cout << "-- test_objects --" << endl; D1 d1; D2 d2; test_pointer(&d1); test_pointer(&d2); // D1 D2 test_reference(d1); test_reference(d2); // D1 D2 test_base(d1); test_base(d2); // Base Base } void test_pointer_to_base_class() { cout << "-- test_pointer_to_base_class --" << endl; Base *pd1 = new D1(); Base *pd2 = new D2(); test_pointer(pd1); test_pointer(pd2); // D1 D2 test_reference(*pd1); test_reference(*pd2); // D1 D2 test_base(*pd1); test_base(*pd2); // Base Base delete pd1; delete pd2; } void test_pointer_to_class() { cout << "-- test_pointer_to_class --" << endl; D1 *pd1 = new D1(); D2 *pd2 = new D2(); test_pointer(pd1); test_pointer(pd2); // D1 D2 test_reference(*pd1); test_reference(*pd2); // D1 D2 test_base(*pd1); test_base(*pd2); // Base Base delete pd1; delete pd2; } int main() { test_objects(); test_pointer_to_base_class(); test_pointer_to_class(); }
Expected output:
-- test_objects -- pointer &d1: D1 pointer &d2: D2 reference d1: D1 reference d2: D2 base d1: Base base d2: Base -- test_pointer_to_base_class -- pointer pd1: D1 pointer pd2: D2 reference *pd1: D1 reference *pd2: D2 base *pd1: Base base *pd2: Base -- test_pointer_to_class -- pointer pd1: D1 pointer pd2: D2 reference *pd1: D1 reference *pd2: D2 base *pd1: Base base *pd2: Base
See it working here
Other entries:
- isPrime: Naive version
- isPrime, Optimization 1: Iterate only until the square root of the number
- isPrime, Optimization 2: Only divide by odd numbers, until the square root of the number
- isPrime, Optimization 3: Skip the divisors that are multiple of 2 or 3
- Keep the previosly generated primes and use them to test the following numbers.
- isPrime, Recursive.