Войти в систему

Home
    - Создать дневник
    - Написать в дневник
       - Подробный режим

LJ.Rossia.org
    - Новости сайта
    - Общие настройки
    - Sitemap
    - Оплата
    - ljr-fif

Редактировать...
    - Настройки
    - Список друзей
    - Дневник
    - Картинки
    - Пароль
    - Вид дневника

Сообщества

Настроить S2

Помощь
    - Забыли пароль?
    - FAQ
    - Тех. поддержка



Пишет yigal_s ([info]yigal_s)
@ 2011-10-22 22:57:00


Previous Entry  Add to memories!  Tell a Friend!  Next Entry
C++ - упражнение #1

namespace Example1_ConstructorVsCast
{
	namespace Intro1
	{
		class A { 		};
		class B	{
		public:
			B(){}
			B(const A&){}
		};
		void trivial()
		{
			A a;
			B b1(a); // this calls B's constructor
			B b2=B(a); // well, the same...
			B b3=(B)a;
			B b4=a;
			b1 = (B)a;
			b1 = static_cast<B>(a);
		}
	}
	namespace Intro2
	{
		class B { };
		class A	{ public: operator B() { return B(); }	};

		void trivial()
		{
			A a;
			B b1(a); // this calls cast-operator of A
			B b2=B(a); // well, the same... I hope
			B b3=(B)a;
			B b4=a;

			b1 = (B)a;
			b1 = static_cast<B>(a);
		}
	}

	// conclusion: both options serve us equivalently well


	namespace Now // now... suppose we have both
	{
		class A;
		class B	{
		public:
			B(){}
			B(const A&){}
		};
		class A { public: operator B() { return B(); }	};

		void nontrivial()
		{
			A a;
			B b1(a); // what happens here? will it compile at all?
			B b2=B(a); // and here???
			B b3=(B)a; // and here????
			B b4=a; // and here???

			// now let's recheck what we've learned:
			b1 = (B)a;
			b1 = static_cast<B>(a);
		}
	}
}