我正在尝试传递对类中函数的引用,但在弄清楚如何做到这一点时遇到了麻烦。所以说我有一个test
这样定义的类
#include <iostream>
class test {
public:
test () {};
~test () {};
void setA (int);
int getA (void);
private:
int a;
};
void test::setA (int A) { a = A; }
int test::getA (void) { return a; }
using namespace std;
int main ()
{
test T;
T.setA(5);
cout << "a = " << T.getA() << endl;
return 0;
}
效果很好,但是如果我想通过引用传递值
#include <iostream>
class test {
public:
test () {};
~test () {};
void setA (int);
int & getA (void);
private:
int a;
};
void test::setA (int & A) { a = A; }
int & test::getA (void) { return a; }
using namespace std;
int main ()
{
test T;
T.setA(5);
cout << "a = " << T.getA() << endl;
return 0;
}
我不知道如何配置setA
通过引用传递。
代码有两个问题。首先,setA的定义与声明不匹配。您必须使声明以引用作为参数。
更改此:
void setA (int);
对此:
void setA (int&);
第二个问题是您试图传递一个r值(5)作为参考。您必须传递一个L值。您可以通过先创建一个int然后通过引用传递它来实现:
int i = 5;
T.setA(i);
完整示例:
#include <iostream>
class test {
public:
test () {};
~test () {};
void setA (int&);
int & getA (void);
private:
int a;
};
void test::setA (int & A) { a = A; }
int & test::getA (void) { return a; }
using namespace std;
int main ()
{
test T;
int i = 5;
T.setA(i);
cout << "a = " << T.getA() << endl;
return 0;
}
当您通过引用传递某些东西给C ++中的函数时,该函数不会自动将参数保留在内存中。因此,您必须先声明它,以便它在整个函数中都保留在内存中。
您尝试作为参考传递的5将超出范围,并在函数启动后立即销毁。声明的i变量会在主函数的末尾销毁。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句