c++ 函数传参 string string& const string &三者的区别

1.string做参数:

#include <bits/stdc++.h>
using namespace std;
void test(string s){
    s="shit";
}
int main(){
    string s{"test"};
    test(s);
    cout<<s<<endl;
}

打印结果:

test

2.string&做参数:

void test(string &s){
    s="shit";
}
int main(){
    string s{"test"};
    test(s);
    cout<<s<<endl;
}

打印结果:

shit

3.const string&做参数:

首先演示一下如果没有const时,直接传入c语言字符串(即"test")的结果:

void test(string &s){
}
int main(){
    test("test");
}

报错:无法用 “const char [5]” 类型的值初始化 “std::__cxx11::string &” 类型的引用(非常量限定)

加上const后就可以了

void test(const string &s){
	cout<<s<<endl;
}
int main(){
    test("test");
}

打印结果:

test

这里没有报错说明const前缀的应用的一部分原因就是为了方便使用c语言字符串。

  • 26
    点赞
  • 97
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 FORTRAN90 中调用 C++ 函数,需要使用 `iso_c_binding` 模块来声明 C++ 函数,并使用 `c_f_pointer` 函数C++ 函数指针转换为 FORTRAN90 中的指针类型。下面是一个示例代码,展示了如何声明并调用 C++ 中的函数: ``` #include <string> #include <iostream> extern "C" { void my_cpp_function(const std::string& str) { std::cout << "The string received in C++ is: " << str << std::endl; } } ``` 在 FORTRAN90 中,您需要使用 `iso_c_binding` 模块来声明 C++ 函数,并使用 `c_f_pointer` 函数函数指针转换为 FORTRAN90 中的指针类型。示例代码如下: ``` program main use iso_c_binding interface subroutine my_cpp_function(str) bind(C, name="my_cpp_function") import :: C_CHAR type(c_ptr), value :: str end subroutine my_cpp_function end interface character(len=20) :: my_string = "Hello from FORTRAN" type(c_ptr) :: my_string_ptr ! Convert the FORTRAN string to a C string pointer call c_f_pointer(c_loc(my_string), my_string_ptr) ! Call the C++ function using the C string pointer call my_cpp_function(c_char_pointer(my_string_ptr)) end program main ``` 在代码中,首先使用 `interface` 关键字声明 C++ 函数 `my_cpp_function`,并使用 `bind(C)` 来指定函数的 C 风格命名。使用 `C_CHAR` 来声明 C++ 函数的参数类型。`c_f_pointer` 函数字符串类型的 `my_string` 转换为指针类型,并将其传递给 `my_cpp_function` 函数。在调用 `my_cpp_function` 函数时,需要使用 `c_char_pointer` 函数字符串指针转换为 C 字符串指针。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值