繁体   English   中英

我试图在我的C ++类中声明一个常量字符串,但是我得到了“无效的类内任务”,我不明白为什么

[英]I'm trying to declare a constant string in my C++ class, but I get an “Invalid in-class assignment”, and I don't understand why

这是代码:

#include <string>

class Config {
public:
    static const std::string asdf = "hello world!";
}

我无法诊断为什么这不起作用

只能在类中初始化整数类型(假设它们被声明为static const )。

这样做:

//Config.h
class Config 
{
public:
    static const std::string asdf; //declaration
    static const int demo_integral = 100; //initialization is allowed!
}

//Config.cpp 
const std::string Config::asdf = "hello world!"; //definition & initialization 
const int Config::demo_integral; //already initialized in the class!

定义应该在.cpp文件中,否则如果在头文件本身中定义它们然后将头文件包含在多个文件中,则会出现多个定义错误!

你不可以做这个。

因为它是静态的,所以必须在类之外定义const std::string asdf在你的类中只是声明,因为static

在你的情况下:

const std::string Config::asdf = "hello world!"

您应该初始化构造函数中的所有数据成员,而不是像这样:

class A
{
    var_t var = value;
};

除了整数类型,静态const成员不能在类定义范围内初始化。 您必须将其拆分,如下所示。

在头文件中:

#include <string>

class Config {
public:
    static const std::string asdf;
};

并在.cpp文件中

const std::string Config::asdf = "hello world!";

你必须在课外声明它:

#include <string>

class Config {
public:
    static const std::string asdf = "hello world!";
}

const std::string Config::asdf = "hello world";

还看这里

从:

http://cplusplus.syntaxerrors.info/index.php?title=Invalid_in-class_initialization_of_static_data_member_of_non-integral_type_%E2%80%98const_char *%E2%80%99

您只能在类定义中首先分配枚举类型的变量或“整数”类型 - int,char,long等。 Char *不是整数类型,因此您只能在全局范围内分配它。

您可以将此作为解决方法:

#include <string>

class Config {
public:
    static const std::string asdf()
    {
       return "Hello World!";
    }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM