0

我想要一个类中的指针数组。这是我尝试过的代码。但我得到一个错误。

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了,它会显示一条消息,例如“您的等式计算的面积是:”有没有更好的方法来进行这种类型的消息传递。

4

3 回答 3

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.

}
于 2012-08-13T16:36:24.900 回答
2

这与它是一个指针数组无关(顺便说一句,使用起来不是特别好的东西,请考虑std::vector<std::string>),但与您尝试初始化的方式有关msg。这是一个(非静态)成员变量,所以你必须在你的类的构造函数中初始化它,而不是在它声明的地方。

class Msg{
    public:
      char *msg[3];

      Msg()
        : msg{ "one"
             , "two"
             , "three" }
      {}

//there are some other method i want to write.....
 };
于 2012-08-13T16:29:52.810 回答
0

我怀疑但我不能肯定地说(你没有发布实际的错误)你得到了一个"too many initializers error"

更改*msg[2]*msg[3]。或将其留空。[]

或去掉“三”。

于 2012-08-13T16:33:26.320 回答