请就指针,转换和值的分配提供一些建议。
我有这个修复类定义:(由gsoap生成)
class LibClass
{
public:
std::string *email; // pointer
int landId; // no pointer
// (....) much more
}
在单独的函数中,我将数据从数据库(informix)分配给上面的类成员。
(...) // just database connection
// The following is informix interface related stuff
ITRow *row;
// define one time this conversions interface
ITConversions *c;
// placeholder for all string types, temporary data container
ITString its("");
ITString colname;
// read result from executed query
while ( row = query.NextRow() ) {
LibClass *ki = new LibClass;
ki->email = new (string);
//ki->landId = new (int); // obviously : error: invalid conversion from 'int*' to 'int'
// I tried :
// invent a new instance
LibClass rki;
//rki = &ki;
//rki.x = 9;
// this is okay but how to bring ki and rki together,
int *a = new int;
rki.x = *a;
// And for understanding, here's what comes next - It seams as i have to hardcode all 30 DB fields... but thats okay for now.
colname="email";
ITValue *v = row->Column( colname );
v->QueryInterface(ITConversionsIID, (void **) &c);
c->ConvertTo( its );
*( ki->email ) = string(its.Data()); // THE DATA TRANSFER - assignment
v->Release();
} // while end
编辑我无法继续这样做,所以我无法批准这些建议,但只想关闭这里,所以我接受最详细的答案。 thx all。
答案 0 :(得分:1)
这是我采取的一种方法。
...
// read result from executed query
while ( row = query.NextRow() ) {
LibClass *ki = new LibClass;
ki->email = new (string); //Needed to create storage
// That's all the setup you need on your object
//Here's what I'd do differently
ki->email = get_column_data(ki->email, "email");
ki->landId = get_column_data(ki->landId, "landId");
...
}
template <typename T>
void get_column_data(T target, string column_name){
//Code to grab column data based on target type and column name
}
...
答案 1 :(得分:1)
很难理解你正在用rki和ki做什么,但你应该有
rki = *ki // (1)
而不是
rki = &ki // (2)
Line(1)取消引用指向类实例的指针,为您留下类实例。
Line(2)为您提供指向类实例的指针,但rki不是类型(LibClass **)
答案 2 :(得分:0)
首先,除非有充分的理由,否则LibClass不应该指向std::string
。 std::string
在内部为您处理所有分配。
class LibClass
{
public:
std::string email; // shouldn't be a pointer
int landId; // no pointer
// (....) much more
}
然后在while
循环中,不再需要初始化email
,您只需将所需的值分配到landId
:
LibClass ki;
// ki.email is initialized to "" already
ki.landId = 9;
// ... other code ....
ki.email = string(its.Data());
或者,如果LibClass 必须是由于某种原因分配的堆(即你需要将它从函数中传出):
LibClass *ki = new LibClass();
// ki->email is initialized to "" already
ki->landId = 9;
// ... other code ....
ki->email = string(its.Data());
// IMPORTANT: somewhere else in your program you muse delete the allocated space
delete ki;