我是面向对象方法和 C++ 编程的新手: 我的问题是:没有实例化任何对象的类指针如何调用该类的成员函数。下面是我今天尝试的工作代码
#include <iostream>
class Base{
public:
Base(){
std::cout << "Base C-tor is called " << std::endl;
}
void fun(){
std::cout << "Base fun() is called " << std::endl;
}
void sorrow(){
std::cout << "Base Sorrow is called " << std::endl;
}
~Base(){
std::cout << "Base D-tor is called " << std::endl;
}
};
int main(){
Base *b1;
b1->fun();
b1->sorrow();
}
下面是这段代码的输出:
Base fun() is called
Base Sorrow is called
最佳答案
尽管调用了未定义的行为,但由于编译器调用非虚拟成员函数的方式,您的代码看起来可以正常工作。对于您的 fun()
和 sorrow()
成员函数,没有执行对实例的访问,因此函数完成就像它工作一样(即使它的调用仍然存在无效)。
如果你声明你的函数virtual
,崩溃的可能性会大大增加(尽管你不能保证任何未定义的行为):
virtual void fun(){
std::cout << "Base fun() is called " << std::endl;
}
virtual void sorrow(){
std::cout << "Base Sorrow is called " << std::endl;
}
调用虚函数需要访问类的实例以获取函数的位置。由于指针未初始化,代码很可能崩溃。
关于c++ - 在不创建实例的情况下调用非静态成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45649636/