Need help about 'new' operator in C++
本问题已经有最佳答案,请猛点这里访问。
我想了解C++中的新操作符和我的代码。我有两个文件A和B,都可以编译。但是我在运行A的二进制文件时,遇到了错误"分段错误"。B的二进制文件工作正常。
"new"操作符在文件b中做什么?
File A
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #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; } |
File B
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #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之间的区别是
1 2 | Animal *animal = new Animal; Cat *cat = new Cat; |