【问题标题】:c++ (non-built in/class) static memberc++(非内置/类)静态成员
【发布时间】:2010-10-15 12:16:27
【问题描述】:
#include <iostream>
#include <string>

class c1
{
 public:
  static std::string m1;
  static unsigned int m2;
};

//std::string c1::m1 = std::string;
unsigned int c1::m2 = 0;

void main()
{
 c1 a;
 //std::cout<<a.m1<<std::endl;
 std::cout<<a.m2<<std::endl;
}

在这个程序中,启用两个注释行会导致第一行出错。

error C2275: 'std::string' : 非法将此类型用作表达式

我做错了什么?

【问题讨论】:

    标签: c++ class static member


    【解决方案1】:

    因为“std::string”是一个类型,而不是一个值。下面是一个可能使这一点更明显的例子:

    #include <iostream>
    #include <string>
    
    class c1
    {
    public:
      static unsigned int m2;
    };
    
    unsigned int c1::m2 = int; // error: int is a type, not a value
    
    void main()
    {
      c1 a;
      std::cout<<a.m2<<std::endl;
    }
    

    【讨论】:

      【解决方案2】:

      错误说明了一切,您正在使用 type std::string 作为要分配的 value。

      要解决此问题,您可以这样做:

      std::string c1::m1 = std::string();
                                      ^^
      

      或者只是

      std::string c1::m1;
      

      【讨论】:

        【解决方案3】:
        std::string c1::m1 = std::string;
        

        应该是这样的

        std::string c1::m1 = "";
        

        【讨论】:

          【解决方案4】:

          错误是由于在该行右侧​​使用了std::string - 您正在尝试将 m1 的 value 初始化为 type @987654322 @。

          您应该会发现像std::string c1::m1 = "Wee - a string!"; 这样的行会起作用。

          【讨论】:

            猜你喜欢
            • 2012-04-13
            • 2016-05-20
            • 1970-01-01
            • 1970-01-01
            • 2014-11-04
            • 1970-01-01
            • 1970-01-01
            • 2014-05-11
            • 1970-01-01
            相关资源
            最近更新 更多