c ++类中的指针数组

Nat*_*ngh 0 c++ arrays pointers 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
}
Run Code Online (Sandbox Code Playgroud)

但它不编译并在类中显示错误,我也想知道如何访问作为类成员的指针数组.如果我错了,请更正语法.

edit:[i want to do]

我有大约12条固定消息,根据情况显示,我设置一个枚举,以得到正确的索引.

enum{
    size,
    area,
    volume,
    //etc 
Run Code Online (Sandbox Code Playgroud)

};

class Msg有一个函数putMsg(int index),cout当我通过枚举时需要msg.如果我通过area它将把一个msg像"你的等式计算的区域是:"是否有更好的方法来做这种类型的消息传递.

Mar*_*ork 6

试试这个:

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.

}
Run Code Online (Sandbox Code Playgroud)