我有一个方法,用于将对象的映射转换为人类可读的键值对.为此,我需要一些字符,如引号,空格和反斜杠,默认情况下将被解释为控制字符,如果在键或值中使用,则需要转义.由于不会有任何重复,我需要快速查找,我假设一个集合将是最好的选择,但作为(对我的知识)你不能锁定一个集合,它可能会被意外更改.
将HashSet作为常量是否是个好主意,有没有办法使它成为不可变的,遵循常量命名约定(UPPER_CASE)以及如何在其中放置初始值是一个好主意?
我无法在类中初始化常量,其中一个常量依赖于其他常量值.
class foo {
private:
const int secondConst;
const int firstConst;
public:
foo(int x) :
firstConst(x),
secondConst(firstConst*3)
{
// constructor code here....
}
}
Run Code Online (Sandbox Code Playgroud)
secondConst是一个垃圾值,我该如何正确初始化它?也许在C++中,一个常量在初始化时不能依赖其他常量?
我编辑了我的帖子.问题实际上是在原始代码中我切换了声明它们的const字段.
我对为变量和文字常量赋值给我感到有点困惑.
例如:
int age = 20;
Run Code Online (Sandbox Code Playgroud)
age是一个变量,20是分配给它的值.
和:
int AGE = 20;
Run Code Online (Sandbox Code Playgroud)
AGE是文字常量,20是分配给它的值.
有什么不同?常量会将主内存中的两个字节作为变量吗?
在C#中是否有相同的功能?
#define TypeConstant int
int main()
{
TypeConstant x = 5;
}
Run Code Online (Sandbox Code Playgroud)
非常感谢你!
编辑:我不确定这与定义常量常量有什么关系,我已明确写出类型常量,而不是常量值!在你投票之前阅读!
我知道实例变量的意思是状态,而常量意味着不变.是否有任何理由(除了惯例)使用常量而不是实例变量?使用常量是否有内存/速度优势?
可以访问C中浮点常量的位表示;
例如,我想分配
uint64_t x = //bit representation of 5.74;
Run Code Online (Sandbox Code Playgroud)
由0x40b7ae14表示
你认为有可能吗?
#include <stdio.h>
#include <stdlib.h>
#define MAX 15 //line that give problems
int linearSearch(int v[], int MAX, int valore);
int main()
{
int ris, valore, v[]={1,1,1,1,1,1,1,1,1,12,1,1,1,1,1};
scanf("%d", &valore);
ris = linearSearch(v, MAX, valore);
printf("%d", ris);
return 0;
}
int linearSearch(int v[], int MAX, int valore)
{
int i;
for (i=0;i<MAX;i++)
{
if(valore==v[i])
return i;
}
return -1;
}
Run Code Online (Sandbox Code Playgroud)
为什么这段代码在编译时报告错误?如果我用预处理器指令替换它,为什么它运行正常
const int MAX = 15;
Run Code Online (Sandbox Code Playgroud) 假设我有这个程序:
const int width = 4;
void test(int&){}
int main() {
test(width);
}
Run Code Online (Sandbox Code Playgroud)
这将无法编译.我注意到名称(例如宽度)的常量值(也是枚举常量)不能通过引用传递.为什么会这样?
来自Apple文档" 学习Swift的基本知识 "
常量是在第一次声明后保持不变的值,而变量是可以更改的值.常量被称为不可变,意味着它不能被改变,并且变量是可变的.如果您知道代码中不需要更改值,请将其声明为常量而不是变量.
然而在REPL中,我可以这样做:
14> let favoriteNumber = 4
favoriteNumber: Int = 4
15> let favoriteNumber = 5
favoriteNumber: Int = 5
Run Code Online (Sandbox Code Playgroud)
我显然遗漏了一些东西:这种差异与编译器或运行时有关,还是其他什么?
我有这个代码:
#include <cstdio>
#include <string>
using namespace std;
const string & func()
{
static string staticString = "one";
printf("%s\n", staticString.c_str());
return staticString;
}
int main( int argc, char ** argv )
{
string firstString = func();
firstString = "two";
printf("%s\n", firstString.c_str());
func();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是
one
two
one
Run Code Online (Sandbox Code Playgroud)
困惑我的部分是,如果我const从func()输出中删除是完全相同的.我期望它是:
one
two
two
Run Code Online (Sandbox Code Playgroud)
如果我从中获取字符串引用func()(当它没有const关键字时),为什么在我func()再次调用时它被重置?