c++ - 在不创建实例的情况下调用非静态成员函数

标签 c++ linux g++

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

相关文章:

c - 如果我 fork() 然后执行 execv(),谁拥有控制台?

c++ - 链接的可执行文件中缺少静态库中的符号

c++ - 如何在 Mac 终端中使用 C++11 支持编译 C++

STL 容器中的 C++11 shared_pointer constness

c++ - c++随机交换数组中的两个元素

c++ - 涉及私有(private)继承的 C 风格向上转型和向下转型

c++ - 为什么我在此函数中出现段错误?

c++ - 函数采用预期大小的数组,向用户发出信号

Linux : how to redirect to a file and to another process

linux - 如何在 linux 中的两个文件中拥有历史记录