gpt4 book ai didi

c++ - 奇怪的访问冲突错误

转载 作者:太空狗 更新时间:2023-10-29 23:46:05 25 4
gpt4 key购买 nike

我写了一个使用继承的程序,一切正常,但一个我认为不应该自然出现的错误。这是我的程序:

class A
{
protected:
int x;
public:
A(){};
~A(){};
A* operator=(const A* other)
{
this->x = other->x;
return this;
}
};
class B : public A
{
public:
B() : A(){};
~B(){};
};
class C
{
protected:
A *a;
public:
C(const A* other){ *(this->a) = other; };
};

int main()
{
B *b = new B();
C *c = new C(b);
return 0;
}

它在语句“this->x = other->x;”中产生执行时间错误。这个呢?

最佳答案

*(this->a) 是未定义的行为,因为 this->a 没有初始化 - 它只是一个悬空指针。

你可以使用 a = new A; *a = other(本例中的 this-> 是多余的),但这不是正确的 C++ 方式——你应该使用 RAII(查找它)——你不会如果需要,则不需要析构函数、赋值运算符或复制构造函数。

此外,operator = 通常通过引用返回 *this

关于c++ - 奇怪的访问冲突错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14076725/

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