c++ - 模板格式化下的结构常量错误

标签 c++ templates

休闲代码告诉我,构造函数中的 o.days 和 days 无法解决,有人知道为什么吗?

template <class T> struct Array{
    int days;
    T * M;
};

类的构造函数:

void constr(Array<Expe> &o){
        o=new Array;
        o->days = days;
        o->M = new Array[o->days];
}

编辑(Luchian Grigore):

template <class T> struct Array{
int days;
T * M;
Array( int size ) : days(size), M(new int[size])
{
}
~Array()
{
   delete[] M;
}
};

当我尝试像这样在 main 中初始化数组时:

int main(){
//Main function of the program. no pre/ post condition.
Array <Expe> A;

错误:

在此处输入代码..\M.cpp:18:15: 错误:没有用于调用“Array::Array()”的匹配函数

最佳答案

Array<Expe> &o是对 Array<Expe> 的引用对象,而不是指针。如果您必须重新初始化它,语法是。

o = Array<Expe>();

然后您通过 . 访问成员:

o.days = days;
o.M = new Array[o.days];

编辑:

我记得昨天的代码。为什么您再次使用适当的构造函数?

template <class T> struct Array{
    int days;
    T * M;
    Array( int size ) : days(size), M(new int[size])
    {
    }
    ~Array()
    {
       delete[] M;
    }
};

关于c++ - 模板格式化下的结构常量错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10124944/

相关文章:

c++ - 链接 64 位内核

c++ - 将值传递给功能模板的最佳方法

C++ 容器、协变和模板

c++ - 如何从模板化流运算符中调用标准流运算符?

c++ - void(U::*)(void) 是什么意思?

c++ - 指针符号和数组

c++ - OpenCV 2.4.3 到 2.4.9 版本变更

c++ - 如何调试由类型特征引起的这个错误?

C++:STL 映射,插入新值不起作用

c++ - 如何制作一个 C++ 模板类,根据模板值的类更改其成员和访问器?