1

type の static メンバーを宣言するのにいくつか問題があります。std::vector<std::string>原則として、それを array に置き換えることができstd::string[]ます。

私は多くの問題を抱えています:それを宣言してstaticから実装(cppファイル)で初期化すると動作しますが、2番目のファイルの最初のクラスから継承する新しいクラスを作成したい場合、それは不平を言います

error: invalid application of ‘sizeof’ to incomplete type ‘std::string []’

ヘッダーで宣言すると、二重宣言に問題があります。

適切な方法は何ですか?extern を使用する必要がありますか? どのように?

私は:

ファイル_A.h:

class A { public: static string s[]; }

ファイル_A.cpp:

string A::s[] = { ... };

file_B.h

class B : public A

file_B.cpp

void B::function()
{
for (string* s = A::s; s != A::s + sizeof(A::s) / sizeof(string); ++s)
}
4

2 に答える 2

1

sizeofオペレーターが何をしているかを誤解しています。実際のデータではなく、データのサイズを示します。場合によっては、データ型のサイズが実際のデータのサイズと同じになることがあります。これは、データ型自体がそれに収まるデータの量を定義する場合にのみ当てはまります。

int a[50]; // 50 ints: sizeof(a) == 50 * sizeof(int)

さらに、sizeof完全なタイプでのみ操作できます。これは完全な型ではありません:

int a[];

不完全な型は、そのサイズを決定するために必要な情報が不足している型です。sizeofここのサイズを取得するために使用することはできませんa

于 2012-11-01T13:40:20.350 に答える
0

Your mistake is that you're trying to sizeof of string s[]. Compiler nothing know about size of your string array.

For example:

void B::function()
{
for (string* s = A::s; s != A::s + sizeof(A::s) / sizeof(string); ++s)
}

In your function instead sizeof(). You can use for (int i = 0; !A::s[i].empty(); ++i) to get size of string array.

PS. If you don't use sizeof(string[]). Your code will be working.

于 2012-11-01T13:24:27.877 に答える