簡體   English   中英

為什么我不能像這樣在QMap上調用插入?

[英]Why can't I call insert on a QMap like this?

嘗試在Qt SDK 4.7.4 for Desktop-MinGW 4.4下編譯以下代碼會導致以下編譯器錯誤:

#include <QtCore/QCoreApplication>
#include <QMap>
struct Buffer
{
   char data[4];
};
// A Bucket needs to reserve 16 chars worth of Buffers
typedef Buffer Bucket[(16 * (sizeof (char))) / (sizeof (Buffer))];
typedef QMap<QString, Bucket *> BucketMap;
int main(int argc, char *argv[])
{
   BucketMap bucket;
   bucket.insert(QString("foo"), new Bucket()); //compile error
   return 0;
}
../test/main.cpp: In function 'int main(int, char**)':
../test/main.cpp:13: error: no matching function for call to 'QMap<QString, Buffer (*)[4]>::insert(QString, Buffer*)'
../../../QtSDK/Desktop/Qt/4.7.4/mingw/include/QtCore/qmap.h:556: note: candidates are: QMap<Key, T>::iterator QMap<Key, T>::insert(const Key&, const T&) [with Key = QString, T = Buffer (*)[4]]
mingw32-make.exe[1]: *** [debug/main.o] Error 1
mingw32-make.exe: *** [debug] Error 2

我嘗試使用std::stringstd::map將其轉換為等效的示例,以達到相同的效果。 我介紹了Qt版本是因為它更緊湊,並且最終是我的項目所需的形式。
我猜想我只是缺少有關如何最終解釋typedef一些信息。 為什么第二個參數顯然要insert Buffer * (而不是Buffer(*)[4] ),我該如何解決?

簡單的答案:類型不匹配。

您實際上需要了解的內容:您不能為數組類型調用new表達式。 因此,以下兩個不相等(第一個不合法):

typedef T TArr[4]; TArr * p = new TArr;  // #1

T * q = new T[4];                        // #2

語言只是無法正常工作。 第二個版本創建一個動態數組,而第一個版本則想創建“ 4 T數組”類型的單個動態對象,這是不可能的。 相反, new TArr實際上與new T[4] ,因此結果是四個T的動態數組 。*

您基本上應該只將地圖的值類型更改為Buffer *std::array<Buffer, 4> *std::unique_ptr<Buffer[]>std::unique_ptr<std::array<Buffer, 4>> ,無論您喜歡哪個。

*)這正是以下代碼非常有問題的原因: template <T> void foo() { T * p = new T; delete p; } template <T> void foo() { T * p = new T; delete p; } template <T> void foo() { T * p = new T; delete p; }假設您說foo<int[4]>(); ...

您的問題出在typedef 請嘗試以下操作:

int bs = sizeof(new Bucket);

並且您將看到bs值為4( INT_PTR );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM