[英]array of pointer in c++ class
我想要一個類中的指針數組。 這是我嘗試的代碼。 但是我得到一個錯誤。
class Msg{
public:
char *msg[2]={
"one",
"two",
"three"
};
//there are some other methods I want to write.....
};
void main(){
Msg msg;
// i want to print msg[] here using a for loop
}
但是它不能編譯,並且在類中顯示錯誤,我也想知道如何訪問屬於類成員的指針數組。 如果我輸入錯誤,請更正語法。
edit:[i want to do]
我有大約12條固定消息,這些消息根據情況顯示,我設置了一個枚舉來獲取正確的索引。
enum{
size,
area,
volume,
//etc
};
class Msg
有一個函數putMsg(int index)
其中cout
需要MSG當我通過一個枚舉。 如果我通過area
,它將放一個味精,例如“根據您的等式計算的面積為:”,是否有更好的方法來進行此類消息傳遞。
嘗試這個:
class Msg{
public:
// Can not initialize objects in the declaration part.
// So just provide the declaration part.
static char const *msg[];
// Note: You had the completely wrong size for the array.
// Best to leave the size blank and let the compiler deduce it.
// Note: The type of a string literal is 'char const*`
// Note: I have made it static so there is only one copy.
// Since the strings are literals this should not affect usage
// But if you wanted one per class you need another technique.
//there are some other method i want to write.....
};
// Now we can provide a definition.
// Note: I still leave the size blank and let the compiler deduce the size.
char const* Msg::msg[]={
"one",
"two",
"three"
};
// Note: main() must return an int.
int main(){
Msg msg;
// i want to print msg[] here using a for loop
// The basic way
for(std::size_t loop = 0;loop < sizeof(Msg::msg)/sizeof(Msg::msg[0]); ++loop)
{
std::cout << Msg::msg[loop] << "\n";
}
// Same as above but using C++11
for(auto loop = std::begin(Msg::msg); loop != std::end(Msg::msg);++loop)
{
std::cout << *loop << "\n";
}
// using algorithms:
std::copy(std::begin(Msg::msg), std::end(Msg::msg), std::ostream_iterator<char *const>(std::cout, "\n"));
// Note: You don't actually need a return statement in main().
// If you don't explicitly provide one then 0 is returned.
}
這與它是一個指針數組(BTW並不是特別好用,請考慮使用std::vector<std::string>
)無關,但是與您嘗試初始化msg
的方式msg
。 這是一個(非靜態)成員變量,因此您必須在類的構造函數中初始化它,而不是在聲明它的地方初始化它。
class Msg{
public:
char *msg[3];
Msg()
: msg{ "one"
, "two"
, "three" }
{}
//there are some other method i want to write.....
};
我懷疑,但我不能肯定地說(您尚未發布實際錯誤),您會收到“初始化程序錯誤太多”的信息 。
將*msg[2]
更改為*msg[3]
。 或將其保留為空白。 []
或刪除“三個”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.