当exit(0)用于退出程序时,不会调用本地作用域的非静态对象的析构函数.但是如果使用return 0则调用析构函数.注意即使我们调用exit()也会清理静态对象.
这种逻辑背后应该有一些原因.我只是想知道它是什么?谢谢.
我对基派生类的关系有这样的疑问。
我知道当我们从基类派生一个类时,派生类将拥有有关基类的所有信息。但基类对派生类一无所知。
那么,为什么这是可以接受的呢?
Base *b=new Derived();
Run Code Online (Sandbox Code Playgroud)
并不是
Derived *d=new Base();.
Run Code Online (Sandbox Code Playgroud)
基本上我需要理解第一个声明的需要?我的意思是,将派生类对象分配给基类指针有什么用?
注意:这不是作业。我正处于学习编程的早期阶段。所以基本上需要了解点滴。如果这是非常基本且已被问到的问题,请忽略。
最近我开始知道这一点 - 如果派生类重新定义了基类成员方法,那么所有具有相同名称的基类方法都会隐藏在派生类中.
#include<iostream>
using namespace std;
class Base
{
public:
int fun()
{
cout<<"Base::fun() called";
}
int fun(int i)
{
cout<<"Base::fun(int i) called";
}
};
class Derived: public Base
{
public:
int fun()
{
cout<<"Derived::fun() called";
}
};
int main()
{
Derived d;
d.fun(5); // Compiler Error
return 0;
}
Run Code Online (Sandbox Code Playgroud)
错误:在函数'int main()'中:第30行:错误:由于-Wfatal-errors,没有匹配函数调用'Derived :: fun(int)'编译终止.
但只是想知道它背后的原因?为什么它不调用Base类的fun(int i)方法,因为Derived类是从Base派生的
可能这可能是一个非常基本的问题,但仍然想了解一些基本概念......
为什么我们将变量定义为 const ?- 在整个程序中保持该特定变量的值恒定。
但是,当我遇到构造函数的初始化列表时,它允许在对象构造期间为 const 变量赋值(例如,我尝试了下面的程序),我对 const 关键字本身的基本概念感到困惑。有人可以澄清这一点吗?
如果允许在对象构造期间更改 const 变量,那么以下程序中 const 变量的用途是什么?我们有针对这些行为的实时场景吗?如果是这样,您能给出一些场景吗?
#include<iostream>
using namespace std;
class Test {
const int t;
public:
Test(int t):t(t) {} //Initializer list must be used
int getT() { return t; }
};
int main() {
Test t1(10);
cout<<t1.getT();
return 0;
}
Run Code Online (Sandbox Code Playgroud) 在C++中,为什么编译器不允许修改以下字符指针,如下所示
#include <iostream>
int main()
{
char* cp = "overflow";
cp[1]='p';
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:在运行时崩溃.
但字符数组允许,
#include <iostream>
int main()
{
char cps[] = "overflow";
cp[1]='p'; // this compiles fine and output is operflow
return 0;
}
Run Code Online (Sandbox Code Playgroud)
只是想知道运行时发生了什么以及崩溃的原因.谢谢.