简体   繁体   中英

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

here's the code:

#include <string>

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

I can't diagnose why this won't work

Only integral types can be initialized in the class (presuming they're declared as static const ).

So do this:

//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!

Definitions should be in .cpp file, or else you will get multiple definition error if you define them in the header file itself and then you include the header file in multiple files!

You cannot do this.

As it is static, it must be defined outside the class ( const std::string asdf inside your class is only declaration, because of the static )

In your case:

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

You should initialize all data members inside constructor, not like this:

class A
{
    var_t var = value;
};

Apart from integral types, static const members cannot be initialized within the class definition scope. You have to split it, as follows.

In header file:

#include <string>

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

And in .cpp file

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

You have to declare it outside of the class:

#include <string>

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

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

Also look here .

From:

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

You are only allowed to first assign variables that are enumeration types or"integral" types -- int, char, long, etc -- inside a class definition. Char* is not an integral type, so you can only assign to it in global scope.

It is possible for you to do this as a workaround:

#include <string>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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