![](/img/trans.png)
[英]I'm trying to make a menu in c++ and I don't understand why it doesn't loop
[英]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";
還看這里 。
從:
您只能在類定義中首先分配枚舉類型的變量或“整數”類型 - 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.