gpt4 book ai didi

c++ - 我可以制作一个#define 并一次性使用它吗?

转载 作者:行者123 更新时间:2023-11-30 01:22:17 24 4
gpt4 key购买 nike

我可以做这样的东西吗?

#define N_VALID "is not a valid ID"  
...
throw N_valid;
...
catch(char *message){
fprintf(stderr,"%s",message);}

最佳答案

是的,除了你抛出的是 const char *,而不是 char *:https://ideone.com/UsnitG

#include <iostream>
using std::cout; using std::endl;

#define N_VALID "is not a valid ID"

void function_throws()
{
throw N_VALID;
}

int main()
{
try
{
function_throws();
}
catch(const char *message) // <= Note the const here!
{
cout << message << endl;
}
}

但是,Joel 是正确的,您应该避免这样做。如果你真的想在此处使用宏,请尝试将其用作 std::exception 对象的参数:https://ideone.com/Dsx1RF

void function_throws()
{
throw invalid_argument(N_VALID);
}

int main()
{
try
{
function_throws();
}
catch(const invalid_argument& ex)
{
cout << "invalid_argument: " << ex.what() << endl;
}
}

关于c++ - 我可以制作一个#define 并一次性使用它吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16675555/

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