holyya.com
2025-09-04 11:13:07 Thursday
登录
文章检索 我的文章 写文章
C++中的default关键字
2023-07-13 16:29:46 深夜i     --     --
default C++程序设计 switch语句 编程语言 控制流程

在C++中,default是一个关键字,用于指定switch语句中的默认情况。也就是说,当switch语句中的所有case语句都不匹配时,default语句就会执行。

下面是一个使用default关键字的示例:


#include <iostream>

using namespace std;

int main() {

  int num;

  cout << "Please enter a number between 1 and 5: ";

  cin >> num;

  switch (num)

    case 1:

      cout << "You entered 1." << endl;

      break;

    case 2:

      cout << "You entered 2." << endl;

      break;

    case 3:

      cout << "You entered 3." << endl;

      break;

    case 4:

      cout << "You entered 4." << endl;

      break;

    case 5:

      cout << "You entered 5." << endl;

      break;

    default:

      cout << "You did not enter a number between 1 and 5." << endl;

      break;

  

  return 0;

}

在上面的代码中,如果用户输入了1到5之间的数字,程序会输出相应的消息。如果用户输入的数字不在1到5之间,则default语句将会执行,并输出一条相应的消息。

除了在switch语句中使用default语句之外,default还可以用作函数模板的参数列表中的默认值。例如:


template<typename T, typename U = int> class MyClass

  // code here

;

在上面的代码中,MyClass是一个函数模板,它有两个参数类型:T和U。参数U有一个默认值int,这意味着如果用户没有为U指定参数,则U将自动变为int类型。

总之,default是C++中的一个非常有用的关键字,它可以在switch语句中指定默认情况,也可以用作函数模板参数列表中的默认值。程序员可以根据需要使用default来简化代码,并使其更易于维护。

  
  
下一篇: 如何安装C++?

评论区

{{item['qq_nickname']}}
()
回复
回复