// Assume class definition for Cat is here. Cat makeCat() { Cat lady = new Cat("fluffy"); return lady; } int main (...) { Cat molly = makeCat(); molly->eatFood(); return 0; }
在molly-> eatFood()中会有“使用免费”错误吗?
解决方法
更正您的程序并创建了类Cat的示例实现:
#include <iostream> #include <string> class Cat { public: Cat(const std::string& name_ = "Kitty") : name(name_) { std::cout << "Cat " << name << " created." << std::endl; } ~Cat(){ std::cout << "Cat " << name << " destroyed." << std::endl; } void eatFood(){ std::cout << "Food eaten by cat named " << name << "." << std::endl; } private: std::string name; }; Cat* makeCat1() { return new Cat("Cat1"); } Cat makeCat2() { return Cat("Cat2"); } int main (){ Cat kit = makeCat2(); kit.eatFood(); Cat *molly = makeCat1(); molly->eatFood(); delete molly; return 0; }
它将产生输出:
Cat Cat2 created. Food eaten by cat named Cat2. Cat Cat1 created. Food eaten by cat named Cat1. Cat Cat1 destroyed. Cat Cat2 destroyed.
我建议你继续学习一本关于C封面的书籍.