![](/img/trans.png)
[英]How do you pass a reference when using a typename as a function argument in C++?
[英]How do you properly create/ pass a reference argument in c++?
对于我的c ++赋值,我只需要创建一个'char',打印它,然后将它作为参考传递给函数,修改它,并重新打印以证明它已被更改。 这似乎很容易,而且我可能犯了一个非常愚蠢的错误,但我不断收到一个错误,上面写着“未解决的外部因素”。 我已经制作了一个.cpp文件,并在我的头文件中声明了一个类。
我的.cpp文件:
#include <iostream>
#include <fstream>
#include "referenceshw.h"
using namespace std;
int main(){
char s = 's';
char& s1 = s;
Ref test;
std::cout << s <<endl;
test.modify(s);
}
void modify(char& s1){
s1 = 'd';
std::cout << s1 <<endl;
std::cout << s <<endl;
}
我的头文件:
#ifndef _REFERENCESHW_H
#define _REFERENCESHW_H
class Ref{
public:
char s;
void modify (char);
};
#endif
你的签名功能不匹配,你的.h你有:
void modify (char);
在.cpp
void modify(char& s1){
只需在.h中添加&之后的char
另外,因为函数是在类声明之外定义的,所以需要在.cpp中的modify之前添加Ref ::。 最后你的.cpp应该是这样的:
void Ref::modify(char& s1){
在你的.h
void modify(char&);
Borgleader是对的。 其他错误:改变
void modify(char& s1)
至
void Ref::modify(char& s1);
另外,您是否尝试在modify()中的代码中引用类成员s1?
s1 = 'd'; // this will change the parameter that was passed in,
// is that what you want?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.