简体   繁体   English

无法分配一个指向模板化类的指针的成员

[英]Can't assign a member which is a pointer to a templatized class

My problem is that in my "Widget" class i've the following declaration: 我的问题是在“ Widget”类中,我有以下声明:

MouseEvent* X;

In a member function I initialize the pointer with an address the normal way: 在成员函数中,我以正常方式用地址初始化指针:

X = new MouseEvent;

Ok, this last line makes the compiler stop at: 好的,这最后一行使编译器停止在:

error C2166: l-value specifies const object 错误C2166:左值指定const对象

All right, a MouseEvent is declared as a typedef to simplify things: 好的,将MouseEvent声明为typedef以简化操作:

typedef Event__2<void, Widget&, const MouseEventArgs&> MouseEvent;

And Event__2 is, as you may imagine as: (basic structure shown): 如您所想,Event__2是:(显示的基本结构):

template <typename return_type, typename arg1_T, typename arg2_T>
class Event__2
{
     ...
};

I don't know where the Event__2 class gets the const qualifier. 我不知道Event__2类在哪里获取const限定词。 Any tips ? 有小费吗 ?

Thanks. 谢谢。

Likely, the member function where you are initializing X is marked as const - something like this. 可能将初始化X的成员函数标记为const-类似这样。

class Foo
{
   int *Bar;

public:

   void AssignAndDoStuff() const
   {
      Bar = new int; // Can't assign to a const object.
      // other code
   }
}

The solution here is either to 解决方案是

  1. Assign to Bar in a separate non-const method, 以单独的非const方法分配给Bar,
  2. change AssignAndDoStuff to be non-const, or 将AssignAndDoStuff更改为非常量,或者
  3. mark Bar as mutable . 将Bar标记为mutable

Pick one of the above: 选择上述之一:

class Foo
{
   mutable int *Bar; // 3

public:
   void Assign() // 1
   {
       Bar = new int; 
   }   
   void DoStuff() const
   {
       // Other code
   }

   void AssignAndDoStuff() // 2
   {
      Bar = new int; 
      // other code
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法将成员变量地址分配给指针 - Can't assign an member variable address to a pointer 类成员:模板化类的向量 - Class member: Vector of templatized class 模板化类的成员函数不能返回指向成员结构的指针? - Member function of a templated class can't return a pointer to member structure? “new”不会为指针分配内存,指针是类的数据成员 - 'new' doesn't allocate memory to pointer which is a data member of a class 无法分配类成员指针变量 - Unable to assign a class member pointer variable 将结构成员函数指针分配给类函数 - Assign struct member function pointer to class function 类型双关语问题:不能重新解释从多个类派生到虚拟成员 function 指针的 class 的成员 function 指针 - Type punning issue: Can't reinterpret_cast member function pointer of class which derives from multiple classes into dummy member function pointer 访问指向存储指向另一个成员类的指针的成员类的指针 - Accessing a pointer to a member class which stores a pointer to another member class 为什么不能为基类的成员分配值? - Why can't I assign a value to a member of the base class? 指向未由对象地址初始化的对象的指针如何将值分配给类的数据成员? - How a pointer to an object which is not initialized by an address of object assign value to data member of class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM