[英]Calling a non-static member function without creating an instance
I am a newbie in object oriented approach and C++ programming as well: My question is: How can a class pointer which is not instantiating any object can call the member function of that class. 我也是面向对象方法和C ++编程的新手:我的问题是:没有实例化任何对象的类指针如何调用该类的成员函数。 below is the working code which I tried today
下面是我今天尝试的工作代码
#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();
}
Below is the output of this piece of code: 下面是这段代码的输出:
Base fun() is called
Base Sorrow is called
Despite invoking undefined behavior, your code gives an appearance of working because of the way the compiler invokes non-virtual member functions. 尽管调用了未定义的行为,但是由于编译器调用非虚拟成员函数的方式,您的代码仍能正常工作。 In case of your
fun()
and sorrow()
member functions, no access to the instance is performed, so the function completes as if it worked (even though its invocation remains invalid). 如果您使用
fun()
和sorrow()
成员函数,则不会执行对该实例的访问,因此该函数会像其正常工作一样完成(即使其调用仍然无效)。
If you declare your functions virtual
, the likelihood of a crash would go up considerably (although you can't guarantee anything with undefined behavior): 如果将函数声明为
virtual
,则崩溃的可能性会大大增加(尽管您不能保证任何行为均未定义):
virtual void fun(){
std::cout << "Base fun() is called " << std::endl;
}
virtual void sorrow(){
std::cout << "Base Sorrow is called " << std::endl;
}
Calling virtual functions require accessing the instance of the class for the location of the function. 调用虚拟函数需要访问类的实例以获取函数的位置。 Since the pointer is uninitialized, the code is very likely to crash.
由于指针未初始化,因此代码很可能崩溃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.