【问题标题】:C++ - initialize static array of char pointersC++ - 初始化 char 指针的静态数组
【发布时间】:2016-11-06 20:08:32
【问题描述】:

如何创建以下指向私有静态类成员的指针数组?

class Auth {
private:
    static char *attribs[3];
    attribs[0]="uid";
    attribs[1]="cn";
    attribs[2]=NULL;
}

我不知道如何以及在何处(.h 中的内容和 .cpp 中的内容?)放置这些行...

【问题讨论】:

  • 你为什么要使用 strdup 来解决这个问题
  • @M.M 只是多次尝试的剩余...

标签: c++ arrays pointers char initialization


【解决方案1】:

auth.h:

class Auth {
private:
    static char *attribs[3];
};

auth.cpp:

char* Auth::attribs[3] = { "uid", "cn", NULL };

【讨论】:

  • 很简单.. 真丢人!谢谢!
  • 这是不合法的。您不能将字符串文字分配给非常量指针。
【解决方案2】:

假设您可以访问 C++11,您应该考虑使用 std::stringstd::vector 而不是 C 样式数组和 C 样式字符串

#include <vector>
#include <string>

class Auth {
    private:
        static std::vector<std::string> attribs;
};

std::vector<std::string> Auth:: attribs = {"uid", "cn"};

【讨论】:

    猜你喜欢
    • 2017-08-26
    • 2011-04-10
    • 1970-01-01
    • 2012-05-24
    • 2023-03-17
    • 2011-04-18
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多