相关疑难解决方法(0)

用户定义的文字为C++添加了哪些新功能?

C++ 11引入了用户定义的文字,这将允许基于现有文本(采用新的文本语法的int,hex,string,float),使得任何类型的将能够具有字介绍.

例子:

// imaginary numbers
std::complex<long double> operator "" _i(long double d) // cooked form
{ 
    return std::complex<long double>(0, d); 
}
auto val = 3.14_i; // val = complex<long double>(0, 3.14)

// binary values
int operator "" _B(const char*); // raw form
int answer = 101010_B; // answer = 42

// std::string
std::string operator "" _s(const char* str, size_t /*length*/) 
{ 
    return std::string(str); 
}

auto hi = "hello"_s …
Run Code Online (Sandbox Code Playgroud)

c++ user-defined-literals c++11

138
推荐指数
8
解决办法
3万
查看次数

二进制文字?

在代码中,我有时会看到人们以十六进制格式指定常量,如下所示:

const int has_nukes        = 0x0001;
const int has_bio_weapons  = 0x0002;
const int has_chem_weapons = 0x0004;
// ...
int arsenal = has_nukes | has_bio_weapons | has_chem_weapons; // all of them
if(arsenal &= has_bio_weapons){
  std::cout << "BIO!!"
}
Run Code Online (Sandbox Code Playgroud)

但是我在这里使用十六进制格式没有意义.有没有办法直接用二进制文件做?像这样的东西:

const int has_nukes        = 0b00000000000000000000000000000001;
const int has_bio_weapons  = 0b00000000000000000000000000000010;
const int has_chem_weapons = 0b00000000000000000000000000000100;
// ...
Run Code Online (Sandbox Code Playgroud)

我知道C/C++编译器不会编译它,但必须有一个解决方法吗?是否有可能在其他语言如Java?

c++

49
推荐指数
8
解决办法
7万
查看次数

标签 统计

c++ ×2

c++11 ×1

user-defined-literals ×1