C++ 函数使用C风格参数:
C风格的字符串参数由一系列的字符组成,将字符作为参数时意味着传递的是地址,可以使用const来禁止对字符参数的修改。
将C风格的字符串作为参数传递给C++函数,表示的方法有三种:
- char数组;
- 用引号括起来的字符串
常量
; - 被设置为字符串的地址的char指针;
将C风格的字符串作为参数传递给C++函数,实际上传递的是字符串的第一个字符的地址。
// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
unsigned int c_int_str(const char* str,char ch);
int main()
{
using namespace std;
char mmm[15] = "minimum";
const char *wail = "ululate";
unsigned int ms = c_int_str(mmm,'m');
unsigned int us = c_int_str(wail,'u');
cout << ms << "m characters in" << mmm << endl;
cout << us << "u characters in" <<wail << endl;
return 0;
std::cout << "Hello World!\n";
}
unsigned int c_int_str(const char* str,char ch)
{
unsigned int count = 0;
while (*str) //quit when *str is '\0'
{
if (*str == ch)
count++;
str++;
}
return count;
}
在函数头中也可以使用char[]表示法:
unsigned int c_int_str(const char str[],char ch);