【问题标题】:What is the difference when generic class is declared with and without using default constructor? [duplicate]使用和不使用默认构造函数声明泛型类有什么区别? [复制]
【发布时间】: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&lt;int&gt; srInt(); 是一个函数。
  • StudentRecord&lt;int&gt; srInt(); 声明了一个名为srInt函数,它不接受任何参数并按值返回StudentRecord&lt;int&gt; 对象。去掉括号来解决它:StudentRecord srInt;`
  • 好吧,但是后面发生了什么,比如编译的时候,
  • @Vishal 正如其他人所说,StudentRecord&lt;int&gt; srInt(); 是一个函数,StudentRecord&lt;int&gt; srInt; 是一个实例变量。

标签: c++


【解决方案1】:

这与模板(“通用类”)无关。


就像int f(); 是一个函数声明一样,StudentRecord&lt;int&gt; srInt();s 是一个函数声明。是的,即使你把它写在一个函数中。

删除(),你会得到一个对象声明。

就是这样!


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

当您编写StudentRecord&lt;int&gt; srInt(-1); 时,这是一个有效的对象声明,因为它不可能是函数声明(-1 不是参数声明)。

如果-1 被替换为更复杂的表达式,它可能会被解释为有效的参数声明这一事实而感到惊讶。喜欢int f(int());这是最令人头疼的解析。


这里没有魔法或奇异之处;你只需要为你想要的东西使用正确的符号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    • 2013-02-03
    • 2010-11-13
    • 2014-11-26
    相关资源
    最近更新 更多