如何在C++中通过引用发送指向函数的指针
How send pointer to function by reference in C++?
如何通过引用将指针发送到函数?例如,我想把它发送到一个函数:
int **example;
谢谢。
只需这样声明:
void f(int*&);
当您将int x
传递给函数foo()
并收到类似的消息时
foo(int& var), here `int&` for `reference to int`, just replace it with whatever reference you want to pass, in your case `foo(int** &)` .
^^^^
如果您想通过引用传递char pointer
(char*),只需执行foo(char* &)
即可。
我的建议不仅针对这种情况,而且针对一般情况:当您对复杂类型有问题时,请使用typedef。它不仅可以帮助你解决这个特殊的问题,还可以了解它是如何更好地工作的:
class Foobar;
typedef Foobar* FoobarPtr;
void function( FoobarPtr &ref );
你的问题让很多人感到困惑,因为"send(pointer to function)"不同于"(send pointer)to(function)"。。。给定你的示例变量,我假设你想要后者。。。
参考方面表示在最后:
return_type function_name(int**& example) // pass int** by ref
万一int*
是您想要传递的,而示例代码中的**
是通过引用传递的尝试——对于int*
,它实际上应该是:
return_type function_name(int*& example) // pass int* by ref
更新
您的代码:
void Input(float **&SparceMatrix1,int &Row1,int &Column1)
{
cin>>Row1; cin>>Column1;
*SparceMatrix1 = new float [Row1];
/*for(int i=0;i<Row1;i++) (*SparceMatrix1)[i]=new float [Column1];*/
}
SparceMatrix1
的类型(拼写为"稀疏"btw)意味着它可以跟踪这样的数据:
float** ---------> float* -----------> float
SparceMatrix1 *SparceMatrix1 **SparceMatrix1
因此,您尝试将*SparceMatrix1
设置为指向Row1
float
s,但SparceMatrix1
还没有指向任何东西,因此您根本无法尊重/遵循它。相反,你应该这样做:
if (cin >> Row1 >> Column1)
{
SparceMatrix1 = new float*[Row1];
for (int i = 0; i < Row1; ++i)
SparceMatrix1[i] = new float[Column1];
}
else
SparceMatrix1 = nullptr; // pre-C++11, use NULL, or throw...
正如你所看到的,正确地完成所有这些事情有点棘手,所以你最好使用std::vector<std::vector<float>>
(这更容易纠正,但已经足够棘手了——你会发现太多关于它们的堆叠式问题)。
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针