我知道关键字virtual
使基类具有多态性,如果我创建一个对象并调用a virtual function
,将根据运行时分配调用相应的函数,但为什么要创建一个具有不同类型的对象.我的意思是
Base *ptr = new Derived;
ptr->virtualfunction(); //calls the function which has implemented in Derived class.
Run Code Online (Sandbox Code Playgroud)
如果我创建一个对象,那么
Derived *ptr = new Derived;
ptr->virtualfunction(); // which does the same without the need of making the function virtual.
Run Code Online (Sandbox Code Playgroud) 我有一系列结构.在初始化期间,我需要在条件基础上初始化.说
struct struct_name[arraySize] = { {1, 'a'}, {2, 'b'},
#if condition
{3, 'c'}
#else
{4, 'd'}
#endif
};
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我使用预处理器指令控制初始化.无论如何,我可以在不使用预处理器指令的情况下进行此条件编译吗?
我有一个程序,其中类T具有静态函数.
static void T::func()
{
m_i=10;
cout<<m_i<<endl;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试在函数定义中添加静态时,编译器抛出错误错误:无法声明成员函数'static void T :: func()'具有静态链接.为什么在定义中不接受静态关键字?