所以,我明白指针是什么,引用什么意思,并且对这个“堆”有一个模糊的理解。当我们开始失去对事物的控制时,就是当我们使用这些概念引入函数和类时,例如发送指针,返回指针等。指针与参考
如果通过引用和传递指针本质上执行相同的功能,那么使用它们的优点是什么?基本上都是通过引用传递并在被调用的函数之外操作对象。
因此,通过参考:
#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