我想知道是否可以在具有多重继承的对象中找到结构的偏移量而不知道任何类型的任何成员。我做知道类型,如果有帮助的话。
我目前正在使用sizeof()
计算偏移量。当我有一个空基类时存在问题,或者在组合两个类进行多重继承时添加了填充。
让我用一个例子来说明问题:
struct A { int x; };
struct B { bool b; }; // Empty struct gives same results
struct C : B, A {};
int main()
{
// Prints: 4 1 8
printf("%i %i %i\n", sizeof(A), sizeof(B), sizeof(C));
C obj;
obj.x = 1;
obj.b = true;
// Simple offset calculations, I can't use these because they both use data members
// Prints: 4 4
printf("%i %i\n", (int)&obj.x - (int)&obj, offsetof(C, x));
// Cast to pointer
char* ptr = reinterpret_cast<char*>(&obj);
A* wrong = reinterpret_cast<A*>(ptr + sizeof(B));
// Prints wrong values because sizeof(B) == 1 wrongly offsets the pointer
printf("%i\n", wrong->x);
// Because of padding this is correct
// Empty base class optimization would simply cast ptr as correct
// How to get the correct offset?
A* correct = reinterpret_cast<A*>(ptr + 4);
// Prints correct value, 1
printf("%i\n", correct->x);
}
答案 0 :(得分:1)
使用
!/usr/bin/perl -w
use DBI;
use DBD::mysql;
use MySQL;
$DBHOST = "mysqlserver.example.com";
$DBNAME = "anydb";
$DBUSER = "userdb";
$DBPASS = "userdbpwd";
$dsn = "dbi:mysql:database=$DBNAME,host=$DBHOST, port=3306";
my $dbh = DBI->connect("DBI:mysql:database=$DBNAME,host=$DBHOST, port=3306", "$DBUSER", "$DBPASS", \%attr);