I'm trying to understand how the hpp, cpp, and main all work together. for this example I'm working on a code that coverts ARGB to RGBA and I'm confused on what to put in each file.
This is my code:
color.hpp
using namespace std;
#include <stdio.h>
#include <stdio.h>
#include <iostream>
#ifndef colors_hpp
#define colors_hpp
/* colors_hpp */
string getHex();
uint32_t fromArgb();
#endif
color.cpp
#include "colors.hpp"
#include <iostream>
#include <stdio.h>
#include <stdarg.h>
#include <stdint.h>
template <typename T>
struct Color
{
public:
/* Works fine!!! */
Color(uint8_t r, uint8_t g, uint8_t b, uint8_t a = 255)
{
buffer((r << 0) | (g << 8) | (b << 16) | (a << 24));
}
Color(const uint32_t argb)
{
buffer = fromArgb(argb);
}
inline uint32_t fromArgb(uint32_t argb)
{
return
// Source is in format: 0xAARRGGBB
((argb & 0x00FF0000) >> 16) | //____RR
((argb & 0x0000FF00)) | //_GG_
((argb & 0x000000FF) << 16) | //__BB_
((argb & 0xFF000000)); //AA____
// Return value is in format: 0xAABBGGRR
}
inline uint8_t getRed(void) const
{
return (buffer >> 0) & 0xFF;
}
inline uint8_t getGreen(void) const
{
return (buffer >> 8) & 0xFF;
}
inline uint8_t getBlue(void) const
{
return (buffer >> 16) & 0xFF;
}
inline uint8_t getAlpha(void) const
{
return (buffer >> 24) & 0xFF;
}
/* Works fine!!!*/
std::string getHex(void) const
{
std::string result = "#";
char colorBuffer[255] = {};
// Order is intentionally end to beginning
sprintf_s(colorBuffer, 255, "%.2X", getAlpha());
result.append(colorBuffer);
sprintf_s(colorBuffer, 255, "%.2X", getBlue());
result.append(colorBuffer);
sprintf_s(colorBuffer, 255, "%.2X", getGreen());
result.append(colorBuffer);
sprintf_s(colorBuffer, 255, "%.2X", getRed());
result.append(colorBuffer);
return result;
}
private:
uint32_t buffer;
};
main.cpp
int main(int argc, char**argv) {
fromArgb(255,255,0,0);
getHex();
}
I'm not able to understand where to use or call the struct or functions, and i'm really confused on what to put in hpp, cpp, and main files.
CodePudding user response:
Some advice
Remove this
template <typename T>
Move
struct Color { ... };
to color.hpp (all of it, you can delete color.cpp, it is not needed).Remove
using namespace std;
from color.hppRemove
string getHex(); uint32_t fromArgb();
from color.hppchange main to this
int main(int argc, char**argv) { Color c; c.fromArgb(255,255,0,0); std::cout << c.getHex() << std::endl; }
The main problem seems to be that you don't know how objects work. In order to use the fromArgb
and getHex
methods you need a Color
object. So in my code I declared a Color
object like this Color c;
and then I used that colour object like this c.fromArgb(255,255,0,0);
and this c.getHex()
. How to use classes and objects is a more important topic than how to organise your code into headers and cpp files.
I haven't tested these changes. If there are any further problems you can't figure out then ask again.