I tried doing a custom class that has an extension method, but I am getting compile time errors. I put this in my .h file:
class Byte
{
public:
Byte();
~Byte();
std::string DataType;
int ColumnWidth;
std::vector<unsigned char> data;
int ToLittleEndianInt() {
long int Int = 0;
int arraySize = this->ColumnWidth;
if (arraySize == 2)
{
Int = this->data[0] | ((int)this->data[1] << 8);
}
else if (arraySize == 1)
{
Int = this->data[0];
}
return Int;
};
};
That throws the error:
Error LNK2019 unresolved external symbol "public: __thiscall Byte::Byte(void)" (??0Byte@@QAE@XZ) referenced in function "public: static void __cdecl DataParser::Parse(class nlohmann::basic_json<class std::map,class std::vector,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,bool,__int64,unsigned __int64,double,class std::allocator,struct nlohmann::adl_serializer>)" (?ParseToDataTable@Parse@@SAXV?$basic_json@Vmap@std@@Vvector@2@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@2@_N_J_KNVallocator@2@Uadl_serializer@nlohmann@@@nlohmann@@@Z)
I also tried declaring it as:
const Byte& ToLittleEndianInt(const Byte& s)const {}
That was the way I saw done in Stephen Prata's C++ Primer, but then I still get errors, and I would have to use it like this in my cpp:
std::vector<unsigned char> test(3);
for (int i = 0; i < 2; i++)
test[i] = i;
Byte CurrentBytes;
CurrentBytes.data = test;
CurrentBytes.ColumnWidth=2;
int results = CurrentBytes.ToLEInt(CurrentBytes);
//instead of this way which is better
int results = CurrentBytes.ToLittleEndianInt();
I then tried putting the declaration outside of the class block, but then I got an error that LEInt wasn't defined,
int Byte::ToLittleEndianInt(){}
When I tried adding int ToLittleEndianInt();
to the public class block, then it complained that it was already defined. What is the right way to add this?
Update:
When I do it as a struct, it works:
struct Byte
{
std::string DataType;
int ColumnWidth;
int StartingPosition;
std::string Column;
std::vector<unsigned char> data;
int ToLEInt() {
long int Int = 0;
int arraySize = this->ColumnWidth;
if (arraySize == 2)
{
Int = this->data[0] | ((int)this->data[1] << 8);
}
else if (arraySize == 1)
{
Int = this->data[0];
}
return Int;
};
std::string ToString()
{
int i;
std::string s = "";
int arraySize = this->ColumnWidth;
for (i = 0; i < arraySize; i++) {
std::string n(1, this->data[i]);
s = s + n;
}
return s;
}
};