我已經實現了通過兩個數字交換功能,這很好。但是,我現在試圖交換兩個字符串,但我收到相同順序的名稱。有人會知道我錯了什麼地方,或者我可以做些什麼來讓名字改變位置?這裏是下面的代碼示例:C++:交換字符參考
#include "stdafx.h"
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
void swapages (int &age1, int &age2);
void swapname(char *person1, char *person2);
int _tmain(int argc, _TCHAR*argv[])
{
char person1[] = "Alex";
char person2[] = "Toby";
int age1 = 22;
int age2 = 27;
cout << endl << "Person1 is called " << person1;
cout << " and is " << age1 << " years old." << endl;
cout << "Person2 is called " << person2;
cout << " and is " << age2 << " years old." << endl;
swapname(person1,person2);
swapages(age1,age2);
cout << endl << "Swap names..." << endl;
cout << endl << "Person1 is now called " << person1;
cout << " and is " << age1 << " years old." << endl;
cout << "Person2 is now called " << person2;
cout << " and is " << age2 << " years old." << endl;
system("pause");
return 0;
}
void swapages(int &age1, int &age2)
{
int tmp = age2;
age2 = age1;
age1 = tmp;
}
void swapname(char *person1, char *person2)
{
char* temp = person2;
person2 = person1;
person1 = temp;
}
好吧,正如你所說,「通過參考」。但我沒有看到任何參考。 –
爲了能夠修改,您必須通過指針('char **',指向指針的指針)或引用('char *&')來傳遞'char *'指針,就像您對int中的int所做的那樣'swapages()')。順便說一句,[數組是邪惡的](http://www.parashift.com/c++-faq/arrays-are-evil.html),所以忘記它並使用['std :: string'](http:// en .cppreference.com/W/CPP /串/ basic_string的)。 – Drop
如果你使用['std :: swap'](http://en.cppreference.com/w/cpp/algorithm/swap)和['std :: string'],你的代碼會更簡單(並且實際工作) (http://en.cppreference.com/w/cpp/string/basic_string)從標準庫。 – Blastfurnace