0

我有两个结构

        template<typename T>
        struct Node{
               T obj;
               Node* next;
               Node* prev;
               Node();
               Node(T a, Node<T>* b=NULL, Node<T>* c=NULL);
        };

        template<typename T>
        struct Monomial : public Node<T>{
               int n;
               Monomial(T coeff = 0, int p = 0) : Node<T>(coeff){ n=p; }
        };

编译器告诉我我做错了什么但我无法弄清楚?

我试图在main函数中这样做:

         Monomial<int> *m1;
         m1->n=5;
         m1->obj=6;

我得到的错误消息是“运行时检查失败#3 - 变量'm1'正在被使用而没有被初始化。”

4

2 回答 2

3

像这样初始化 m1。

Monomial<int> *m1 = new Momonial<int>();
于 2013-04-23T00:16:29.557 回答
3

声明指针不会创建对象。

// Allocate memory for the object and create it.

Monomial<int> *m1 = new Monomial<int>;
m1->n=5;
m1->obj=6;

// When you are done with the object, destroy it and deallocate memory.
delete m1;

在堆栈上交替创建对象

Monomial<int> m1;
m1.n=5;
m1.obj=6;

无需致电newdelete

于 2013-04-23T00:17:05.360 回答