我正在从 course on Udacity 学习 C++ .
你能给我解释一下为什么 setGrades()
被定义为一个传递指针到值的函数吗?为什么按值传递会出错?在下面的代码中,我省略了 printGrades()
和 setID()
的定义。
#include<iostream>
using namespace std;
const int SIZE = 5;
template <class T>
class StudentRecord
{
private:
const int size = SIZE;
T grades[SIZE];
int studentId;
public:
StudentRecord(T defaultInput);
void setGrades(T* input);
void setId(int idIn);
void printGrades();
};
template<class T>
StudentRecord<T>::StudentRecord(T defaultInput)
{
for(int i=0; i<SIZE; ++i)
grades[i] = defaultInput;
}
template<class T>
void StudentRecord<T>::setGrades(T* input)
{
for(int i=0; i<SIZE;++i)
{
grades[i] = input[i];
}
}
int main()
{
StudentRecord<int> srInt(-1);
srInt.setId(111111);
int arrayInt[SIZE]={4,3,2,1,4};
srInt.setGrades(arrayInt);
srInt.printGrades();
return 0;
}
输出应该是:
ID# 111111: 4
3
2
1
4
最佳答案
C++ 不允许按值传递内置的 C 风格数组。可以通过引用传递数组或传递指向数组第一个元素的指针。给定这样的指针,就可以访问整个数组。
通过指针传递在文献中并不是一个常用术语,但人们不断地创造类似的术语,这表明了某种真正的需要。该术语背后的想法如下:按值传递指针,但目标是让函数将指向的对象作为左值访问(通常通过按引用传递该对象来实现)。
关于c++ - 为什么这是一个传递指针函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48072554/