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

发布于 2024-08-31 23:27:14 字数 452 浏览 4 评论 0原文

在 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 或其他东西。

In C++ I wanted to define a constant that I can use in another function, A short answer on how to do this will be fine..

Lets say at the beginning of my code I want to define this constant:

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

I don't know what type to use to define the "clear" string... I'm so confused.

Later on I want to use it within a function:

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

 return 0;
}

How would I define the string up top, and use the string down below? I heard char only had one character and things... I'm not sure how to use , since it says it's converting string into const char or something.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

别靠近我心 2024-09-07 23:27:14

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

您可能需要考虑的一件事是使其成为一个函数。这避免了全局构建顺序的令人讨厌的依赖关系。

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

char* isn't quite a char. char* is basically a string (it's what strings were before C++ came along).

For illustration:

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

char[] degrades to char*, so you'll often see functions take a char*.

To convert std::string to const char*, you can simply call:

std::string s;
s.c_str()

In this case, it's common to use the preprocessor to define your OS. This way you can use the compiler to do the platform specific stuff:

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

One thing you may want to consider is making it a function. This avoids nasty dependencies of global construction order.

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

What it looks like you're trying to do is this:

#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
究竟谁懂我的在乎 2024-09-07 23:27:14

问题是,你的变量超出了范围。如果我在括号内声明某些内容,则它仅存在于括号内。

if( foo ){
    const char* blah = "blah";
}

一旦我们离开 if 语句,变量 blah 就消失了。您需要将其非本地实例化到您编写的任何括号中。因此:

void Bar(){
    const char* blah = "blah";
    if( foo ){
        //blah exists within here
    }
}

但是,blah 将不会存在于 Bar 之外。得到它?

Here's the problem, you're suffering from going out of scope with the variables. If I declare something within brackets, it only exists within the brackets.

if( foo ){
    const char* blah = "blah";
}

Once we leave the if statement, the variable blah disappears. You'll need to instantiate it non-locally to whatever brackets you write. Hence:

void Bar(){
    const char* blah = "blah";
    if( foo ){
        //blah exists within here
    }
}

However, blah will not exist outside of Bar. Get it?

冬天旳寂寞 2024-09-07 23:27:14

另一种选择是创建一个具有一堆静态方法的类。为每个命令创建一个新方法。类似于:

// in sys-commands.h
class SystemCommands {
public:
    static char const* clear();
    static char const* remove();
};

这为您提供了一些不错的实施选项。最好的办法是为您在编译时选择的每个平台提供一个单独的实现文件。

// in sys-commands-win32.cpp
#include "sys-commands.h"
char const* SystemCommands::clear() { return "cls"; }
char const* SystemCommands::remove() { return "erase /f/q"; }

// in sys-commands-macosx.cpp
#include "sys-commands.h"
char const* SystemCommands::clear() { return "/usr/bin/clear"; }
char const* SystemCommands::remove() { return "/bin/rm -fr"; }

编译哪个文件将决定将使用哪个命令集。您的应用程序代码将如下所示:

#include <cstdlib>
#include "sys-commands.h"

int main() {
    std::system(SystemCommands::clear());
    return 0;
}

编辑: 我忘记提及,由于多种原因,我更喜欢静态函数而不是全局常量。如果没有别的事,您可以使它们非常量而不改变它们的类型 - 换句话说,如果您必须根据运行时设置选择命令集,则用户代码不必更改或甚至意识到发生了这样的变化。

Yet another option is to create a class with a bunch of static methods. Create a new method for each command. Something like:

// in sys-commands.h
class SystemCommands {
public:
    static char const* clear();
    static char const* remove();
};

This gives you a few nice options for the implementation. The nicest one is to have a separate implementation file for each platform that you select during compile time.

// in sys-commands-win32.cpp
#include "sys-commands.h"
char const* SystemCommands::clear() { return "cls"; }
char const* SystemCommands::remove() { return "erase /f/q"; }

// in sys-commands-macosx.cpp
#include "sys-commands.h"
char const* SystemCommands::clear() { return "/usr/bin/clear"; }
char const* SystemCommands::remove() { return "/bin/rm -fr"; }

Which file gets compiled will determine which command set will be used. Your application code will look like:

#include <cstdlib>
#include "sys-commands.h"

int main() {
    std::system(SystemCommands::clear());
    return 0;
}

Edit: I forgot to mention that I prefer static functions to global constants for a bunch of reasons. If nothing else, you can make them non-constant without changing their types - in other words, if you ever have to select the command set based on runtime settings, the user code does not have to change or even be aware that such a change occurred.

聽兲甴掵 2024-09-07 23:27:14

您可以使用通用头文件并根据系统链接到不同的模块:

// systemconstants.hpp

#ifndef SYSTEM_CONSTANTS_HPP_INCLUDED
#define SYSTEM_CONSTANTS_HPP_INCLUDED

namespace constants {
   extern const char cls[];  // declaration of cls with incomplete type
}

#endif

如果是 Linux,只需编译并链接到此文件:

// linux/systemconstants.cpp

#include "systemconstants.hpp"

namespace constants {
   extern const char cls[] = "clear";
}

如果是 Windows,只需编译并链接到此文件:

// windows/systemconstants.cpp

#include "systemconstants.hpp"

namespace constants {
   extern const char cls[] = "cls";
}

系统特定的翻译单元可以是放置在特定的子目录(linux/、windows/ 等)中,在构建过程中可以自动选择其中一个。这扩展到许多其他事物,而不仅仅是字符串常量。

You can use a common header file and link to different modules depending on the systen:

// systemconstants.hpp

#ifndef SYSTEM_CONSTANTS_HPP_INCLUDED
#define SYSTEM_CONSTANTS_HPP_INCLUDED

namespace constants {
   extern const char cls[];  // declaration of cls with incomplete type
}

#endif

In case of Linux, just compile and link to this one:

// linux/systemconstants.cpp

#include "systemconstants.hpp"

namespace constants {
   extern const char cls[] = "clear";
}

In case of Windows, just compile and link to this one:

// windows/systemconstants.cpp

#include "systemconstants.hpp"

namespace constants {
   extern const char cls[] = "cls";
}

System-specific translation units could be placed in specific subdirectories (linux/, windows/, etc) of which one could be automatically selected during the build process. This extends to many other things, not just string constants.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文