指向对象类型检查的c ++指针 [英] c++ pointers to objects type checking
问题描述
如何验证指针所指向的对象有效
How do I verify that an object being pointed by a pointer is valid
相关代码
LookupTable<Product *> table;
Product temp = *table[selection];
// if *table[selection] is not a product, program crashes...
这里是查找表:
#ifndef LOOKUPTABLE_H
#define LOOKUPTABLE_H
#include <iostream>
#include <string>
using namespace std;
#define MAXRANGE 10
template <class T>
class LookupTable
{
private:
T *aptr[MAXRANGE];
int rangeStart[MAXRANGE];
int rangeEnd[MAXRANGE];
int numRanges;
public:
T defaultValue;
bool failedRangeCheck;
std::string failReason;
// Constructor
LookupTable()
{
numRanges = 0;
defaultValue = T();
}
void addRange(int start, int end)
{
std::cout << "Created a new range... Start: " << start << " / End: " << end << endl;
failedRangeCheck = false;
//lines omitted because not working anyway
if ( !failedRangeCheck )
{
//set ranges
rangeStart[numRanges] = start;
rangeEnd[numRanges] = end;
//build new generic array with end-start+1 positions
//set pointer to point to it
aptr[numRanges] = new T[ end - start + 1 ];
numRanges++;
}
else
{
std::cout << "Range overlapped another range." << endl;
std::cout << failReason << endl;
}
}
T &operator[](int value) // Overloaded [] operator
{
for ( int i = 0; i < numRanges; i++ )
{
if ( (value >= rangeStart[i]) && (value <= rangeEnd[i]) )
{
return aptr[i][value - rangeStart[i]];
}
}
return defaultValue;
}
~LookupTable()
{
delete[] aptr;
numRanges = 0;
}
};
#endif
推荐答案
Based on the code of LookupTable
that you posted in a subsequent question, this question can finally be answered. (Really, I think you ought to just put that code here and remove the other question.)
table[selection]
或者返回对表中某个条目的引用(如果找到了选择),否则返回对默认初始化对象的引用.当LookupTable专用于指针类型(例如代码中的Product*
)时,默认初始化的对象将是NULL指针.
table[selection]
either returns a reference to an entry in the table (if the selection is found) or otherwise a reference to a default-initialized object. When LookupTable is specialized for a pointer type (such as the Product*
in your code) then the default-initialized object will be a NULL pointer.
因此,对于代码中的LookupTable<Product*>
,表达式table[selection]
要么将结果指向表中找到的Product
指针,要么为NULL Product
指针.
So, for the LookupTable<Product*>
in your code, the expression table[selection]
is either going the result in a pointer to a Product
found within the table or else a NULL Product
pointer.
因此,您应该立即获取指针值并进行检查,而不是立即取消引用table[selection]
的结果并将其分配给Product
对象的尝试.
Consequently, instead of immediately dereferencing the result of table[selection]
and trying to assign it to a Product
object, you should actually take the pointer value and examine it.
这将通过类似于以下代码的代码来实现:
This would be accomplished with code similar to:
Product* result = table[selection];
if(result != NULL)
{
Product temp = *result;
// do something with temp, etc, etc
}
else
{
cout << "invalid product code" << endl;
}
这篇关于指向对象类型检查的c ++指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!