C – 返回对象的函数

前端之家收集整理的这篇文章主要介绍了C – 返回对象的函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
// 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封面的书籍.

原文链接:https://www.f2er.com/c/114406.html

猜你在找的C&C++相关文章