【发布时间】:2020-04-23 16:33:47
【问题描述】:
我在下面定义了一个通用类,
带有成员参数的数组,即T grades[5];
当我声明这个类的对象时,使用
StudentRecord<int> srInt();
然后调用类的成员函数,使用
srInt.setGrades(arrayInt);
我收到一个错误,
error: request for member ‘setGrades’ in ‘srInt’, which is of non-class type ‘StudentRecord<int>()’
srInt.setGrades(arrayInt);
但是当我使用(下面)声明类并尝试调用相同的函数时,它可以工作
StudentRecord<int> srInt;
//header file for main.cpp
#include<iostream>
using namespace std;
const int SIZE=5;
template <class T>
class StudentRecord
{
private:
const int size = SIZE;
T grades[5];
public:
void setGrades(T* input);
};
template<class T>
void StudentRecord<T>::setGrades(T* input)
{
for(int i=0; i<SIZE;++i)
{
grades[i] = input[i];
}
}
我的问题是声明类有什么区别,
StudentRecord<int> srInt();
v/s
StudentRecord<int> srInt;
【问题讨论】:
-
StudentRecord<int> srInt();是一个函数。 -
StudentRecord<int> srInt();声明了一个名为srInt的函数,它不接受任何参数并按值返回StudentRecord<int>对象。去掉括号来解决它:StudentRecordsrInt;` -
好吧,但是后面发生了什么,比如编译的时候,
-
@Vishal 正如其他人所说,
StudentRecord<int> srInt();是一个函数,StudentRecord<int> srInt;是一个实例变量。
标签: c++