gpt4 book ai didi

C++:定义简单常量以供使用?

转载 作者:搜寻专家 更新时间:2023-10-31 00:22:53 25 4
gpt4 key购买 nike

在 C++ 中,我想定义一个我可以在另一个函数中使用的常量,关于如何做到这一点的简短回答会很好..

假设在我的代码开头我想定义这个常量:

//After #includes
bool OS = 1; //1 = linux
if (OS) {
const ??? = "clear";
} else {
const ??? = "cls";
}

我不知道用什么类型来定义“清晰”的字符串……我很困惑。

稍后我想在一个函数中使用它:

int foo() {
system(::cls); //:: for global

return 0;
}

我如何定义顶部的字符串,并使用下面的字符串?我听说 char 只有一个字符和其他东西...我不确定如何使用 ,因为它说它正在将字符串转换为 const char 或其他东西。

最佳答案

char* 不完全是 charchar* 基本上是一个字符串(这是 C++ 出现之前的字符串)。

举例说明:

int array[N];  // An array of N ints.
char str[N]; // An array of N chars, which is also (loosely) called a string.

char[] 降级为 char*,因此您经常会看到函数采用 char*

要将 std::string 转换为 const char*,您可以简单地调用:

std::string s;
s.c_str()

在这种情况下,通常使用预处理器来定义您的操作系统。这样你就可以使用编译器来做平台特定的事情:

#ifdef OS_LINUX
const char cls[] = "clear";
#elif OS_WIN
const char cls[] = "cls";
#endif

您可能要考虑的一件事是使其成为一个函数。这避免了对 global construction order 的讨厌依赖。 .

string GetClearCommand() {
if (OS == "LINUX") {
return "clear";
} else if (OS == "WIN") {
return "cls";
}
FAIL("No OS specified?");
return "";
}

看起来你正在尝试做的是这样的:

#include <iostream>
using namespace std;

#ifdef LINUX
const char cls[] = "LINUX_CLEAR";
#elif WIN
const char cls[] = "WIN_CLEAR";
#else
const char cls[] = "OTHER_CLEAR";
#endif

void fake_system(const char* arg) {
std::cout << "fake_system: " << arg << std::endl;
}

int main(int argc, char** argv) {
fake_system(cls);
return 0;
}

// Then build the program passing your OS parameter.
$ g++ -DLINUX clear.cc -o clear
$ ./clear
fake_system: LINUX_CLEAR

关于C++:定义简单常量以供使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2794079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com