Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > C/C++ программирование > Общие вопросы C/C++
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 09.04.2013, 20:54   #1
intmain
Играюсь с Python
Форумчанин
 
Аватар для intmain
 
Регистрация: 12.12.2012
Сообщений: 340
Вопрос forward declaration ?

Чтобы инициализировать вектор2 другими векторами2/3/4 я перегрузил конструктор и написал выше структур форвард декларации чтобы компилятор знал что они есть. Но он все равно мне пишет что так - неверно, а как правильно?
Код:
struct Vector2;
struct Vector3;
struct Vector4;

struct Vector2 
{
	float x, y;
	Vector2() { x = y = 0.0f; };
	Vector2(float _x, float _y) { x = _x; y = _y; };
	Vector2(Vector2& v) { x = v.x; y =v.y; };
	Vector2(Vector3& v) { x = v.x; y =v.y; };
	Vector2(Vector4& v) { x = v.x; y =v.y; };


	void print() { printf("%f %f", x, y); };
};

struct Vector3 
{
	float x, y, z;
	Vector3() { x = y = z = 0.0f; };
	Vector3(float _x, float _y, float _z) { x = _x; y = _y; z = _z; };
};

struct Vector4 
{
	float x, y, z, w;
	Vector4() { x = y = z = w = 0.0f; };
	Vector4(float _x, float _y, float _z, float _w) { x = _x; y = _y; z = _z; w = _w; };
};
Ошибки vc++ 2005
Цитата:
gamemath.h(14) : error C2027: use of undefined type 'Vector3'
gamemath.h(5) : see declaration of 'Vector3'
gamemath.h(14) : error C2228: left of '.x' must have class/struct/union
gamemath.h(14) : error C2027: use of undefined type 'Vector3'
gamemath.h(5) : see declaration of 'Vector3'
gamemath.h(14) : error C2228: left of '.y' must have class/struct/union
gamemath.h(15) : error C2027: use of undefined type 'Vector4'
gamemath.h(6) : see declaration of 'Vector4'
gamemath.h(15) : error C2228: left of '.x' must have class/struct/union
gamemath.h(15) : error C2027: use of undefined type 'Vector4'
gamemath.h(6) : see declaration of 'Vector4'
gamemath.h(15) : error C2228: left of '.y' must have class/struct/union
Что ел то - в долг, что жил то - зря.
Для избранных. ))
Секретные разработки
intmain вне форума Ответить с цитированием
Старый 09.04.2013, 21:01   #2
BDA
МегаМодератор
СуперМодератор
 
Аватар для BDA
 
Регистрация: 09.11.2010
Сообщений: 7,291
По умолчанию

Код:
struct Vector2
{
	float x, y;
	Vector2() { x = y = 0.0f; };
	Vector2(float _x, float _y) { x = _x; y = _y; };
	Vector2(Vector2& v) { x = v.x; y =v.y; };
	void print() { printf("%f %f", x, y); };
};

struct Vector3: public Vector2
{
	float z;
	Vector3() { x = y = z = 0.0f; };
	Vector3(float _x, float _y, float _z) { x = _x; y = _y; z = _z; };
};

struct Vector4: public Vector3
{
	float w;
	Vector4() { x = y = z = w = 0.0f; };
	Vector4(float _x, float _y, float _z, float _w) { x = _x; y = _y; z = _z; w = _w; };
};
Самое быстрое исправление (можно еще, возможно, сократить код).
Пишите язык программирования - это форум программистов, а не экстрасенсов. (<= это подпись )

Последний раз редактировалось BDA; 09.04.2013 в 21:04.
BDA вне форума Ответить с цитированием
Старый 09.04.2013, 21:11   #3
intmain
Играюсь с Python
Форумчанин
 
Аватар для intmain
 
Регистрация: 12.12.2012
Сообщений: 340
По умолчанию

Так в вашем варианте пропало преобразование с вектора4 в вектор2

вектор2 какой-то вектор(вектор4)
Vector4 v4(1,2,3,4);
Vector2 v2(v4)
v2 = (1,2)
Что ел то - в долг, что жил то - зря.
Для избранных. ))
Секретные разработки
intmain вне форума Ответить с цитированием
Старый 09.04.2013, 21:18   #4
BDA
МегаМодератор
СуперМодератор
 
Аватар для BDA
 
Регистрация: 09.11.2010
Сообщений: 7,291
По умолчанию

Оно не пропало, просто вектор4 приводится к вектору2 "автоматически", т.к. является производным классом от вектора2.
Пишите язык программирования - это форум программистов, а не экстрасенсов. (<= это подпись )
BDA вне форума Ответить с цитированием
Старый 09.04.2013, 21:38   #5
intmain
Играюсь с Python
Форумчанин
 
Аватар для intmain
 
Регистрация: 12.12.2012
Сообщений: 340
Лампочка

Точно, извиняюсь. это преобразование благодаря наследаванию похоже.
А вектор4 в этом случае будет получен автоматически из вектора2 ?

Vector2 v2(1,2);
Vector4 v4(v2)
v4 = (1, 2, 0, 0)

У меня студия съела мой вариант с форвард декларациями, правда пришлось все тела ф-й прятать в cpp /.

h
Код:
struct Vector2;
struct Vector3;
struct Vector4;

struct Vector2 
{
	float x, y;

	Vector2();
	Vector2(float _x, float _y);
	Vector2(const Vector2 &v);
	Vector2(const Vector3 &v);
	Vector2(const Vector4 &v);

	void print() { printf("%f %f", x, y); };
};
cpp
Код:
Vector2 :: Vector2() { x = y = 0.0f; };
Vector2 :: Vector2(float _x, float _y) { x = _x; y = _y; };
Vector2 :: Vector2(const Vector2 &v) { x = v.x; y =v.y; };
Vector2 :: Vector2(const Vector3 &v) { x = v.x; y =v.y; };
Vector2 :: Vector2(const Vector4 &v) { x = v.x; y =v.y; };
Что ел то - в долг, что жил то - зря.
Для избранных. ))
Секретные разработки
intmain вне форума Ответить с цитированием
Старый 09.04.2013, 21:49   #6
BDA
МегаМодератор
СуперМодератор
 
Аватар для BDA
 
Регистрация: 09.11.2010
Сообщений: 7,291
По умолчанию

Нет, вектор4 не может быть автоматически получен из вектора2. Для него Вы должны описать конструктор преобразования из вектора2 в вектор4.
Пишите язык программирования - это форум программистов, а не экстрасенсов. (<= это подпись )
BDA вне форума Ответить с цитированием
Старый 10.04.2013, 12:40   #7
Somebody
Участник клуба
 
Регистрация: 08.10.2007
Сообщений: 1,185
По умолчанию

Мне кажется, наследование Vector3 от Vector2 как-то нематематично, ведь это скорее Vector2 - частный случай Vector3, где z == 0.
Somebody вне форума Ответить с цитированием
Старый 10.04.2013, 18:43   #8
intmain
Играюсь с Python
Форумчанин
 
Аватар для intmain
 
Регистрация: 12.12.2012
Сообщений: 340
Лампочка

Цитата:
Мне кажется, наследование Vector3 от Vector2 как-то нематематично
Сделал без наследования. Три отдельных структуры, но они могут друг в друга преобразовываться и друг с другом взаимодействовать на уровне отдельных операторов.

Код:
#include <stdlib.h>
#include <stdio.h>

struct Vector2;
struct Vector3;
struct Vector4;

struct Vector2 
{
	float x, y;

	Vector2();
	Vector2(float _x, float _y);
	Vector2(const Vector2 &v);
	Vector2(const Vector3 &v);
	Vector2(const Vector4 &v);

	Vector2& operator=( const float &f);
	Vector2& operator=( const Vector2 &v);
	Vector2& operator=( const Vector3 &v);
	Vector2& operator=( const Vector4 &v);

	void set(float _x, float _y);


	void print() { printf("%f %f\n", x, y); };
};

struct Vector3 
{
	float x, y, z;
	Vector3();
	Vector3(float _x, float _y, float _z);
	Vector3(const Vector2 &v);
	Vector3(const Vector3 &v);
	Vector3(const Vector4 &v);

	Vector3& operator=( const float &f);
	Vector3& operator=( const Vector2 &v);
	Vector3& operator=( const Vector3 &v);
	Vector3& operator=( const Vector4 &v);

	void set(float _x, float _y, float _z);


	void print() { printf("%f %f %f\n", x, y, z); };
};

struct Vector4 
{
	float x, y, z, w;
	Vector4();
	Vector4(float _x, float _y, float _z, float _w);
	Vector4(const Vector2 &v);
	Vector4(const Vector3 &v);
	Vector4(const Vector4 &v);

	Vector4& operator=( const float &f);
	Vector4& operator=( const Vector2 &v);
	Vector4& operator=( const Vector3 &v);
	Vector4& operator=( const Vector4 &v);

	void set(float _x, float _y, float _z, float _w);

	void print() { printf("%f %f %f %f\n", x, y, z, w); };

};

// Vector2 add
Vector2 operator+( Vector2& a, float f );
Vector2 operator+( Vector2& a, Vector2& b );
Vector2 operator+( Vector2& a, Vector3& b );
Vector2 operator+( Vector2& a, Vector4& b );

Vector2& operator+=( Vector2& a, float f );
Vector2& operator+=( Vector2& a, Vector2& b );
Vector2& operator+=( Vector2& a, Vector3& b );
Vector2& operator+=( Vector2& a, Vector4& b );

// Vector3 add
Vector3 operator+( Vector3& a, float f );
Vector3 operator+( Vector3& a, Vector2& b );
Vector3 operator+( Vector3& a, Vector3& b );
Vector3 operator+( Vector3& a, Vector4& b );

Vector3& operator+=( Vector3& a, float f );
Vector3& operator+=( Vector3& a, Vector2& b );
Vector3& operator+=( Vector3& a, Vector3& b );
Vector3& operator+=( Vector3& a, Vector4& b );


// Vector4 add
Vector4 operator+( Vector4& a, float f );
Vector4 operator+( Vector4& a, Vector2& b );
Vector4 operator+( Vector4& a, Vector3& b );
Vector4 operator+( Vector4& a, Vector4& b );

Vector4& operator+=( Vector4& a, float f );
Vector4& operator+=( Vector4& a, Vector2& b );
Vector4& operator+=( Vector4& a, Vector3& b );
Vector4& operator+=( Vector4& a, Vector4& b );

// Vector2 sub
Vector2 operator-( Vector2& a, float f );
Vector2 operator-( Vector2& a, Vector2& b );
Vector2 operator-( Vector2& a, Vector3& b );
Vector2 operator-( Vector2& a, Vector4& b );

Vector2& operator-=( Vector2& a, float f );
Vector2& operator-=( Vector2& a, Vector2& b );
Vector2& operator-=( Vector2& a, Vector3& b );
Vector2& operator-=( Vector2& a, Vector4& b );


// Vector3 sub
Vector3 operator-( Vector3& a, float f );
Vector3 operator-( Vector3& a, Vector2& b );
Vector3 operator-( Vector3& a, Vector3& b );
Vector3 operator-( Vector3& a, Vector4& b );

Vector3& operator-=( Vector3& a, float f );
Vector3& operator-=( Vector3& a, Vector2& b );
Vector3& operator-=( Vector3& a, Vector3& b );
Vector3& operator-=( Vector3& a, Vector4& b );

// Vector4 sub
Vector4 operator-( Vector4& a, float f );
Vector4 operator-( Vector4& a, Vector2& b );
Vector4 operator-( Vector4& a, Vector3& b );
Vector4 operator-( Vector4& a, Vector4& b );

Vector4& operator-=( Vector4& a, float f );
Vector4& operator-=( Vector4& a, Vector2& b );
Vector4& operator-=( Vector4& a, Vector3& b );
Vector4& operator-=( Vector4& a, Vector4& b );

// Neg
Vector2 operator-( const Vector2 &v);
Vector3 operator-( const Vector3 &v );
Vector4 operator-( const Vector4 &v );

Vector2 operator/( Vector2& v, const float f);
Vector2 operator*( Vector2& v, const float f);

Vector3 operator/( Vector3& v, const float f);
Vector3 operator*( Vector3& v, const float f);

Vector4 operator/( Vector4& v, const float f);
Vector4 operator*( Vector4& v, const float f);

Vector2& operator/=( Vector2& v, const float f);
Vector2& operator*=( Vector2& v, const float f);

Vector3& operator/=( Vector3& v, const float f);
Vector3& operator*=( Vector3& v, const float f);

Vector4& operator/=( Vector4& v, const float f);
Vector4& operator*=( Vector4& v, const float f);
Как правильно заинлайнить эти операторы ? Может мне их в описание структур переместить?
Что ел то - в долг, что жил то - зря.
Для избранных. ))
Секретные разработки
intmain вне форума Ответить с цитированием
Старый 10.04.2013, 19:07   #9
_Bers
Старожил
 
Регистрация: 16.12.2011
Сообщений: 2,329
По умолчанию

Как правильно заинлайнить эти операторы ? Может мне их в описание структур переместить?


-- ага
_Bers вне форума Ответить с цитированием
Старый 10.04.2013, 21:04   #10
intmain
Играюсь с Python
Форумчанин
 
Аватар для intmain
 
Регистрация: 12.12.2012
Сообщений: 340
Вопрос

Посмотрел в дебаге дизассемблер похоже никакого инлайна нет.
Код вектора, как видите операторы в описании структуры.

Код:
#pragma once

#define INLINE

struct Vector2;
struct Vector3;
struct Vector4;
...

typedef struct Vector4
{
	union 
	{

		struct 
		{
			float x;
			float y;
			float z;
			float w;
		};
		float v[4];
	};

	Vector4();
	Vector4(float _x, float _y, float _z, float _w);
    Vector4(const float &f);
	Vector4(const float *f);
	Vector4(const Vector2 &v2);
	Vector4(const Vector3 &v3);
	Vector4(const Vector4 &v4);

	INLINE void set(float _x, float _y, float _z, float _w);

	INLINE const Vector4 operator+(const Vector4 &v) const;
	INLINE const Vector4 operator-(const Vector4 &v) const;
	INLINE const Vector4 operator-() const;
	INLINE const Vector4 operator/(float f)       const;
	INLINE const Vector4 operator*(float f)       const;

	INLINE Vector4& operator+=(const Vector4 &v);
	INLINE Vector4& operator-=(const Vector4 &v);
	INLINE Vector4& operator*=(float f);
	INLINE Vector4& operator/=(float f);

	INLINE Vector4& operator=(const float &f);
	INLINE Vector4& operator=(const Vector2 &v2);
	INLINE Vector4& operator=(const Vector3 &v3);
	INLINE Vector4& operator=(const Vector4 &v4);

} Vector4;
Код.
f += f * 2.0f;

Дизассемблер.
Код:
	f += f * 2.0f;
00411C16  push        ecx  
00411C17  fld         dword ptr [__real@40000000 (424984h)] 
00411C1D  fstp        dword ptr [esp] 
00411C20  lea         eax,[ebp-0D4h] 
00411C26  push        eax  
00411C27  mov         ecx,offset f (4262A4h) 
00411C2C  call        Vector4::operator* (4113E8h) 
00411C31  push        eax  
00411C32  mov         ecx,offset f (4262A4h) 
00411C37  call        Vector4::operator+= (411131h)
а если определить макрос #define INLINE inline, то вообще линкер ругается что не найдена реализация

Цитата:
1>main.obj : error LNK2019: unresolved external symbol "public: struct Vector4 & __thiscall Vector4:perator+=(struct Vector4 const &)" (??YVector4@@QAEAAU0@ABU0@@Z) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "public: struct Vector4 & __thiscall Vector4:perator=(struct Vector2 const &)" (??4Vector4@@QAEAAU0@ABUVector2@@@Z ) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "public: struct Vector3 & __thiscall Vector3:perator=(struct Vector2 const &)" (??4Vector3@@QAEAAU0@ABUVector2@@@Z ) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "public: struct Vector2 const __thiscall Vector2:perator-(void)const " (??GVector2@@QBE?BU0@XZ) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "public: struct Vector2 & __thiscall Vector2:perator=(struct Vector2 const &)" (??4Vector2@@QAEAAU0@ABU0@@Z) referenced in function _main
Что ел то - в долг, что жил то - зря.
Для избранных. ))
Секретные разработки
intmain вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Проблема с forward declaration Theseus Общие вопросы C/C++ 0 02.01.2013 19:17
Мой браузер Forward jekaz Софт 15 09.04.2010 19:45
Forward declaration из чужого namespace futureteamleader Общие вопросы C/C++ 1 17.10.2009 04:46
[Pascal Error] test_component.pas(43): E2037 Declaration of 'MouseUp' differs from previous declaration Altera Компоненты Delphi 3 10.03.2008 19:44