所以,我明白指針是什麼,引用什麼意思,並且對這個「堆」有一個模糊的理解。當我們開始失去對事物的控制時,就是當我們使用這些概念引入函數和類時,例如發送指針,返回指針等。指針與參考
如果通過引用和傳遞指針本質上執行相同的功能,那麼使用它們的優點是什麼?基本上都是通過引用傳遞並在被調用的函數之外操作對象。
因此,通過參考:
#include <iostream>
class student{
public:
int semesterHours;
float gpa;
};
void defRefS(student &refS);
void defPointerS(student *Ps);
void defValueS(student cS);
int main()
{
student s;
defRefS(s); //Here,
std::cout << "\nBack in main we have " << s.semesterHours << " hours";
std::cout << "\nBack in main the GPA is: " << s.gpa;
student *Ps = &s;
defPointerS(&s); //And here is where I get confused
std::cout << "\nBack in main we have " << s.semesterHours << " hours";
std::cout << "\nBack in main the GPA is: " << s.gpa;
defValueS(s);
std::cout << "\nBack in main object S has: " << s.semesterHours << " hours";
std::cout << "\nBack in main object S has: " << s.gpa << " GPA\n\n";
}
void defRefS(student &refS) //Passing by reference to object
{
refS.gpa = 4.0;
refS.semesterHours = 12;
std::cout << "\n------------- Reference Function ------------";
std::cout << "\n\nObject S has: " << refS.semesterHours << " hours";
std::cout << "\nObject S has: " << refS.gpa << " GPA";
}
void defPointerS(student *Ps) //Passing a pointer to the object
{
Ps->gpa = 5.0;
Ps->semesterHours = 14;
std::cout << "\n\n------------- Pointer Function ---------------";
std::cout << "\n\nNow object S has: " << Ps->semesterHours << " hours";
std::cout << "\nNow object S has: " << Ps->gpa << " GPA";
}
void defValueS(student cS) //Passing the object by value
{
cS.gpa = 100;
cS.semesterHours = 50;
std::cout << "\n\n------------- Value Function ------------------";
std::cout << "\n\nObject S has: " << cS.semesterHours << " hours";
std::cout << "\nObject S has: " << cS.gpa << " GPA";
}
按引用傳遞本質上允許的符號是類似的,因爲,我想,在各方面refS
是的s
對象。所以,這導致使用函數來操縱對象的簡單方法。
傳遞指針很容易理解。它只是一個指向對象的指針。雖然在以上代碼中如何處理:
void defRefS(student &refS);
void defPointerS(student *Ps);
void defValueS(student cS);
所有這些函數是否只定義爲與學生類一起使用?那麼,這些函數只能將參考,指針和對象的值傳遞給這個特定的類?
defRefS(s); //Here,
defPointerS(&s); //And here is where I get confused
defValueS(s);
如果按引用傳遞,你不應該傳遞一個對象的地址嗎?所以,對我而言,它更多地在參考函數中傳遞指針函數的參數。
函數defPointerS
被定義爲接受指針;我正在發送地址?
誰告訴你這個所謂的「堆」不應該支付的「教你的C++」。取而代之的是一本好書。 – 2012-02-12 20:18:10
@KerrekSB我沒有看到教授動態管理變量的常見實現的問題 – 2012-02-12 20:41:23
@SethCarnegie:一百個困惑的SO問題,應該從來都不足以成爲我的理由...... – 2012-02-12 20:43:13