gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:12:46 25 4
gpt4 key购买 nike

我的问题是在我的“Widget”类中有以下声明:

MouseEvent* X;

在成员函数中,我以正常方式用地址初始化指针:

X = new MouseEvent;

好的,最后一行让编译器停止在:

error C2166: l-value specifies const object

好吧,MouseEvent 被声明为 typedef 以简化事情:

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

而 Event__2 就像您想象的那样:(显示的基本结构):

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

我不知道 Event__2 类从哪里获得 const 限定符。有什么建议吗?

谢谢。

最佳答案

很可能,您在其中初始化 X 的成员函数被标记为 const - 类似这样。

class Foo
{
int *Bar;

public:

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

这里的解决方案是

  1. 在一个单独的非常量方法中分配给 Bar,
  2. 将 AssignAndDoStuff 更改为非常量,或者
  3. 将 Bar 标记为可变

选择以上之一:

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
}
}

关于c++ - 无法分配一个指向模板化类的指针的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/384159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com