Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/maven/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用和不使用默认构造函数声明泛型类有什么区别?_C++ - Fatal编程技术网

C++ 使用和不使用默认构造函数声明泛型类有什么区别?

C++ 使用和不使用默认构造函数声明泛型类有什么区别?,c++,C++,我在下面定义了一个泛型类, 成员参数为数组,即T等级[5] 当我声明这个类的对象时,使用 StudentRecord<int> srInt(); srInt.setGrades(arrayInt); StudentRecord<int> srInt; 我犯了个错误 error: request for member ‘setGrades’ in ‘srInt’, which is of non-class type ‘StudentRecord<int>

我在下面定义了一个泛型类, 成员参数为数组,即
T等级[5]

当我声明这个类的对象时,使用

StudentRecord<int> srInt();
srInt.setGrades(arrayInt);
StudentRecord<int> srInt;
我犯了个错误

error: request for member ‘setGrades’ in ‘srInt’, which is of non-class type ‘StudentRecord<int>()’
     srInt.setGrades(arrayInt);
错误:请求'srInt'中的成员'setGrades',该成员为非类类型'StudentRecord()'
srInt.setGrades(arrayInt);
但当我使用(下面)声明类并尝试调用同一个函数时,它是有效的

studentrecordsrint;
//main.cpp的头文件
#包括
使用名称空间std;
常数int SIZE=5;
模板
班级学生记录
{
私人:
常量int size=大小;
T级[5];
公众:
无效设置等级(T*输入);
};
模板
无效StudentRecord::setGrades(T*输入)
{

对于(inti=0;i这与模板无关(“泛型类”)


就像
int f();
是函数声明一样,
StudentRecord srInt();
s是函数声明。是的,即使在函数中编写它

删除
()
,您将得到一个对象声明

就这样


有些人称之为“最烦人的语法分析”,尽管它实际上并不是一个这样的例子。它在一定程度上涉及到一些相同的语法/语言规则

编写
studentrecordsrint(-1);
时,这是一个有效的对象声明,因为它不可能是函数声明(
-1
不是参数声明)

如果将
-1
替换为更复杂的表达式,可能会惊讶于它被解释为有效的参数声明。例如
int f(int());
。这是最麻烦的解析



这里没有什么神奇或奇怪的地方;你只需要使用正确的符号就可以了。

StudentRecord srInt();
是一个函数。
StudentRecord srInt()
声明一个名为
srInt
的函数,该函数不带任何参数,并按值返回一个
StudentRecord
对象。去掉括号来解决它:StudentRecord srInt;`好的,但是后面发生了什么,比如编译时,@Vishal,正如其他人所说的
StudentRecord srInt();
是一个函数,
StudentRecord 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();
StudentRecord<int> srInt;