C++ 程序在运行时崩溃
这段代码有什么问题,我的程序突然停止,没有指出崩溃的原因,我试图做的是使用派生类中的类成员(通过继承),反之亦然:C++ 程序在运行时崩溃,c++,C++,这段代码有什么问题,我的程序突然停止,没有指出崩溃的原因,我试图做的是使用派生类中的类成员(通过继承),反之亦然: #include <iostream> using namespace std; class Base { public: void attribBase(); }; class Derived : public Base { public: void attribDerived(); }; void Base::attribBase() }
#include <iostream>
using namespace std;
class Base
{
public:
void attribBase();
};
class Derived : public Base
{
public:
void attribDerived();
};
void Base::attribBase()
}
Derived d;
d.attribDerived();
}
void Derived::attribDerived()
{
Base b;
b.attribBase();
}
int main()
{
Base b;
Derived d;
b.attribBase();
d.attribDerived();
return 0;
}
#包括
使用名称空间std;
阶级基础
{
公众:
void attribBase();
};
派生类:公共基
{
公众:
void attribDerived();
};
void Base::attribBase()
}
导出d;
d、 属性派生();
}
void-Derived::attribDerived()
{
碱基b;
b、 attribBase();
}
int main()
{
碱基b;
导出d;
b、 attribBase();
d、 属性派生();
返回0;
}
您的程序具有无限递归。
因为发生了堆栈溢出。
然后这个过程就终止了
中断无限函数调用。问题是无限循环。attribDevered()函数调用attribBase()函数,然后attribBase()调用attribDevered(),然后attribDevered()调用attribBase()……这些函数在没有条件停止循环的情况下相互调用 根据编译器的不同,不会出现错误,因为没有语法和逻辑错误。循环可以工作,但我们知道它没有任何用处 我还从您写的“反之亦然”中得到了一个印象,您认为attribDervied()函数是通过基类调用其attribBase()函数的。但是,请记住,继承意味着派生类将获得基类拥有的所有内容的副本。Attrib派生()没有为attribBase()搜索其类之外的函数。因此,attrib派生()只是调用其同级函数(派生类中的attribBase())
希望这能澄清您的问题:)您有无限递归
attribDerived()
调用attribBase()
,它调用attribDerived()
b.attribBase()
创建一个派生对象,该对象调用d.attribDevered()创建调用b.attribBase()的基对象的代码>代码>创建。。。。无限递归你真的应该缩进你的代码。当您将所有内容刷新到编辑窗口的左边距时,很难看到一个类或函数的开始和结束位置。您没有通过继承做任何事情。当派生调用attrbiBase时,它是在一个完全独立的对象中进行的。它是一个简单的--attribDerived
调用attribBase
和attribBase
调用attribDerived
。