Programación General > C/C++
clases en diferentes ficheros y stdafx.h
(1/1)
picyo:
-Hola, cuando creo clases desde por ejemplo, el programa principal, no tengo ningún problema. Ahora "superado" eso, quiero implementar clases usando archicos "*.cpp" y "*.h"
--- Código: C++ ---// Punto.h#ifndef PuntoH#define PuntoHclass Punto{private double x,y;public: Punto(): Punto(double a, double b); ~Punto(); };#endif y el archivo *cpp
--- Código: C++ ---#include "Punto.h"Punto::Punto(){x=y=0;} Punto::~Punto(){}
y el main()
--- Código: C++ ---// main_clases.cpp : main project file. //#include "stdafx.h"#include <iostream> using namespace System;using namespace std; int main(array<System::String ^> ^args){ Console::WriteLine(L"Hello World"); return 0;}
Al compilar me salen estos errores y warnings:
--- Código: C++ --- Warning 1 warning C4627: '#include "Punto.h"': skipped when looking for precompiled header use c:Visual StudioejerciciosBegining Visual C++ 2008Examplesclasesmain_clasesmain_clasesPunto.cpp 1 main_clases Error 2 fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "stdafx.h"' to your source? c:Visual StudioejerciciosBegining Visual C++ 2008Examplesclasesmain_clasesmain_clasesPunto.cpp 9 main_clases Warning 3 warning C4627: '#include <iostream>': skipped when looking for precompiled header use c:Visual StudioejerciciosBegining Visual C++ 2008Examplesclasesmain_clasesmain_clasesmain_clases.cpp 4 main_clases Error 4 fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "stdafx.h"' to your source? c:Visual StudioejerciciosBegining Visual C++ 2008Examplesclasesmain_clasesmain_clasesmain_clases.cpp 15 main_clases
Respecto el fichero stdfx.h no lo he querido poner ( uso Visual Studio) porque prefiero usar un método lo mas global posible, no depender de un compilador u otro ( usar al maximo el ISO, mientras no tenga necesidad de usar WindowForms, etc) y es por eso que veo que se substtituye por los #ifndef PuntoH... del archivo de cabecera. Pero al crear el archivo punto.cpp es cuando me da error al compilar.
* ¿ De qué forma puedo substituir correctamente las típocas lineas de #Pragma y fichero stdfx.h ?
* ¿ Es realmente útil el archivo de encabezado "*.h", no bastaría con crear una clase desde su fichero "*.cpp" ?
Gracias!
( y gracias Villa :p )
picyo:
Bueno he visto que desde opciones se puede eliminar esto del stdfx.h, y asi lo he hecho ( es aconsejable?)
Respecto la otra pregunta, aun tengo dudas del porque "oficialmete" se separan tanto los ficheros para hacer una clase
Amilius:
Efectivamente usar precompilados (incluir stdfx.h en los cpp) es opcional, pero reduce el tiempo de compilación así que no es necesario en proyectos chicos. De todas formas me parece que podrías usar otros compiladores y tener un stdfx.h en blanco.
¿Por que tener separado el .h del .cpp?
1. Por diseño: separación de interfaz de implementación, ocultar detalles de implementación. Muy importante al crear DLLs para mantener compatibilidad entre versiones.
2. Reduce tiempo de compilación: Tienes que tener en cuenta que antes de compilar un ".cpp" prácticamente se hace un "copy/paste" de todos los "include" dentro del archivo .cpp.
Por lo anterior cuanto más grande sea tu proyecto cuanto más importante es tener un .h y un .cpp por clase. Para códigos pequeños, como algún ejemplo de uso, no es relevante.
picyo:
Ok, merci!
Entonces el encabezado (lo que seria para todo el mundo)seria siempre algo como :
--- Código: C++ ---//clase.hclass clase{}public:int una;int funcion(int a);;
y la implementacion(que seia por parte de cada programador según como querría gestionar la clase?):
--- Código: C++ --- #include "clase.h"clase::funcion(int a){ // dónde pongo la variable que devuelve la función? a=2*a; return a; }}
Asi es ams o menos como lo entiendo, pero siguiendo un ejemplo del libtro de Ivor, no veo nada claro :
fichero .h
--- Código: C++ ---#pragma once class CBox{public: CBox(double lv = 1.0, double wv = 1.0, double hv = 1.0);public:public: ~CBox(void); private: // Length of a box in inches double m_Length; // Width of a box in inches double m_Width; // Height of a box in inches double m_Height;public: double GetHeight(void) { return m_Height; }public: double GetWidth(void) { return m_Width; }public: double GetLength(void) { return m_Length; }public: double Volume(void) const { return m_Length*m_Width*m_Height; }public: // Overloaded addition operator CBox operator+(const CBox& aBox) const;public: // Multiply a box by an integer CBox operator*(int n) const;public: // Divide one box into another int operator/(const CBox& aBox) const;}; fichero .cpp
--- Código: C++ ---#include "Box.h" CBox::CBox(double lv, double wv, double hv): m_Length(0){ lv = lv <= 0.0 ? 1.0 : lv; // Ensure positive wv = wv <= 0.0 ? 1.0 : wv; // dimensions for hv = hv <= 0.0 ? 1.0 : hv; // the object m_Length = lv>wv ? lv : wv; // Ensure that m_Width = wv<lv ? wv : lv; // length >= width m_Height = hv;} CBox::~CBox(void){} // Overloaded addition operatorCBox CBox::operator+(const CBox& aBox) const{ // New object has larger length and width of the two, // and sum of the two heights return CBox(m_Length > aBox.m_Length ? m_Length : aBox.m_Length, m_Width > aBox.m_Width ? m_Width : aBox.m_Width, m_Height + aBox.m_Height);} // Multiply a box by an integerCBox CBox::operator*(int n) const{ if(n%2) return CBox(m_Length, m_Width, n*m_Height); // n odd else return CBox(m_Length, 2.0*m_Width, (n/2)*m_Height); // n even} // Divide one box into anotherint CBox::operator/(const CBox& aBox) const{ // Temporary for number in horizontal plane this way int tc1 = 0; // Temporary for number in a plane that way int tc2 = 0; tc1 = static_cast<int>((m_Length/aBox.m_Length))* static_cast<int>((m_Width/aBox.m_Width)); // to fit this way tc2 = static_cast<int>((m_Length/aBox.m_Width))* static_cast<int>((m_Width/aBox.m_Length)); // and that way //Return best fit return static_cast<int>((m_Height/aBox.m_Height))*(tc1>tc2 ? tc1 : tc2);}
El fichero de cabecera lo entiendo, es como "construir" la clase. Pero a la hora de implementarla en el fichero cpp, no entiendo como se "inventa" ( para mi claro) ciertas cosas. Por ejemplo ( uno de tantos..) en el fichero .h esta esto :
--- Código: C++ ---public: double GetWidth(void) { return m_Width; y digo yo, en el archivo . cpp vere su implementación... pues no no la veo..pero por ejemplo veo que implementa cosas que no están en el archivo de cabecera, tales como :
--- Código: C++ ---// Divide one box into anotherint CBox::operator/(const CBox& aBox) const{ // Temporary for number in horizontal plane this way int tc1 = 0; // Temporary for number in a plane that way int tc2 = 0; tc1 = static_cast<int>((m_Length/aBox.m_Length))* static_cast<int>((m_Width/aBox.m_Width)); // to fit this way tc2 = static_cast<int>((m_Length/aBox.m_Width))* static_cast<int>((m_Width/aBox.m_Length)); // and that way //Return best fit return static_cast<int>((m_Height/aBox.m_Height))*(tc1>tc2 ? tc1 : tc2);} Eso entendería mucho mejor que se hiciese en el main() de cualquier programa, el hecho que se haga aquí me tiene totalmente perdido...
Navegación
Ir a la versión completa