繁体   English   中英

调用非静态成员函数而不创建实例

[英]Calling a non-static member function without creating an instance

我也是面向对象方法和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;
}

调用虚拟函数需要访问类的实例以获取函数的位置。 由于指针未初始化,因此代码很可能崩溃。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM