相关疑难解决方法(0)

通过NULL类指针调用类方法

我有以下代码片段:

class ABC{
public:
        int a;
        void print(){cout<<"hello"<<endl;}
};

int main(){
        ABC *ptr = NULL:
        ptr->print();
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

它运行成功.有人可以解释一下吗?

c++

38
推荐指数
6
解决办法
8466
查看次数

为什么我能够使用无效的类指针进行函数调用

在下面的代码片段中,虽然指针未初始化,但仍然可以成功调用

temp *ptr;
ptr->func2();
Run Code Online (Sandbox Code Playgroud)

是由于C++语言属性,还是VC++ 6编译器是犯规的?

class temp {
public:
    temp():a(9){}
    int& func1()
    {
        return a;
    }
    bool func2(int arg)
    {
        if(arg%2==0)
            return true;
        return false;
    }
    int a;
};

int main(int argc, char **argv)
{
    temp *ptr;
    int a;
    cin>>a;
    if(ptr->func2(a))
    {
        cout<<"Good poniner"<<endl;
    }
    ptr->func1(); // Does not crash here
    int crashere=ptr->func1();// But does crash here 
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ pointers function

6
推荐指数
2
解决办法
687
查看次数

标签 统计

c++ ×2

function ×1

pointers ×1