我尝试做一个具有扩展方法的自定义类,但遇到编译时错误。我把它放在我的.h文件中:
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;
};
};
抛出错误:
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)
我也尝试将其声明为:
const Byte& ToLittleEndianInt(const Byte& s)const {}
那是我在Stephen Prata的C ++ Primer中看到的方式,但是后来我仍然遇到错误,我必须在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();
然后我尝试将声明放在类块之外,但随后出现一个错误,提示未定义LEInt,
int Byte::ToLittleEndianInt(){}
当我尝试将int ToLittleEndianInt();
添加到公共类块时,它抱怨说它已被定义。添加此内容的正确方法是什么?
当我将其用作结构时,它会起作用:
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;
}
};