我有一個包含指向物件的指標的陣列。每個物件都有一個名為name的string型別的資料成員。
我想使用模板化的qsort函式對其進行排序。再次注意,陣列中的每個元素都是一個指向物件的指標。但是,我收到錯誤:
error C2227: left of '->name' must point to class/struct/union/generic type
在這一行:
return strcmp(a->name, b->name);
在編譯時。
為什么我收到這個錯誤?
這是完整代碼(我使用 Visual Studio 2019):
#include <cstdlib>
#include <stdio.h>
#include <string.h>
//----------------------------------------------------------------------
class my_type {
public:
char name[10];
my_type(char* source) {
strcpy(name, source); // assume data are valid
}
};
//----------------------------------------------------------------------
template <typename a_type>
int compare(const void* pa, const void* pb)
{
a_type* a = (*(a_type**)pa);
a_type* b = (*(a_type**)pb);
return strcmp(a->name, b->name);
}
//----------------------------------------------------------------------
int main()
{
my_type**a;
int n = 5;
a = new my_type * [n]; // allocate the array.
for (int i = 0; i < n; i ) {
char buf[100];
_itoa(i, buf, 10);
a[i] = new my_type(buf); // allocate each element of the array.
}
qsort(a, n - 1, sizeof(a[0]), compare<my_type*>); // sort them
for (int i = 0; i < n; i )// print the sorted elements
printf("%s ", a[i]->name);
for (int i = 0; i < n; i )
delete a[i]; // delete each element
delete[] a; // delete array
getchar();
}
//----------------------------------------------------------------------
uj5u.com熱心網友回復:
名稱是交流字串。有什么理由不使用 stdlib 中的 c 字串嗎?您將無法使用模板編譯代碼?還是 std::sort ?
無論如何,問題是當您呼叫模板時,您將型別定義為指標。你最終得到一個指向指標的指標,它沒有欄位“名稱”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/352373.html
下一篇:C 條件執行取決于型別
