在C ++中需要有关'new'运算符的帮助

时间:2017-06-13 05:39:18

标签: c++

我想了解C ++中的 new 运算符以及我的代码会发生什么。 我有2个文件A和B,两个都可以编译。但是当运行A.Binary of B的二进制文件工作正常时,我正面临错误“ Segmentation fault ”。

“new”运算符在文件B中做了什么?

  

档案A

#include <iostream>
using namespace std;

class Animal
{
    public:
    virtual void eat() { std::cout << "I'm eating generic food."<< endl; }
};

class Cat : public Animal
{
    public:
    void eat() { std::cout << "I'm eating a rat." << endl;}
};

void func(Animal *xyz){ 
    xyz->eat();
}

int main()
{
    Animal *animal ;
    Cat *cat ;
    func(animal);
    func(cat);
    return 0;
}
  

档案B

#include <iostream>
using namespace std;

class Animal
{
    public:
    virtual void eat() { std::cout << "I'm eating generic food."<< endl; }
};

class Cat : public Animal
{
    public:
    void eat() { std::cout << "I'm eating a rat." << endl;}
};

void func(Animal *xyz){ 
    xyz->eat();
}

int main()
{
    Animal *animal = new Animal;
    Cat *cat = new Cat;
    func(animal);
    func(cat);
    return 0;
}

文件A和B之间的差异是

Animal *animal = new Animal;
Cat *cat = new Cat;

1 个答案:

答案 0 :(得分:1)

new运算符为对象分配内存,然后调用构造函数对其进行初始化。在文件A中,您不初始化对象,因此将未初始化的指针传递给func,从而导致分段错误。