簡體   English   中英

你如何在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM