0

请就指针以及值的转换和分配提供一些建议。

我有这个修复类定义:(由 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

编辑我无法继续这样做,所以我不能批准这些建议,但只想在这里关闭,所以我接受最详细的答案。谢谢大家。

4

3 回答 3

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
}
...
于 2011-01-17T15:44:52.083 回答
1

很难理解你在用 rki 和 ki 做什么,但你应该有

rki = *ki // (1)

代替

rki = &ki // (2)

第 (1) 行取消引用指向类实例的指针,为您留下一个类实例。

第 (2) 行为您提供了指向类实例的指针,但 rki 不是类型 (LibClass **)

于 2011-01-17T15:46:36.560 回答
0

首先,std::string除非有充分的理由,否则 LibClass 不应该有指向 a 的指针。 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;
于 2011-01-17T15:58:58.203 回答