C++完全是新手

C++ dought completely Novice

本文关键字:新手 C++      更新时间:2023-10-16
#include<iostream>
using namespace std;
class Animal
{
    private:
        string name;
    public:
        Animal()
        {
            cout << "Animal created" << endl;
        }
        Animal(const Animal& other):
            name(other.name){
                cout << "Animal created by copying" << endl;
        }
        ~Animal()
        {
            cout << "Animal destroyed" << endl;
        }
        void setName(string name)
        {
            this->name = name;
        }
        void speak()const{
            cout << "My name is: " << name << endl;
    }
};
Animal createAnimal()
{
    Animal a;
    a.setName("Bertia");
    return a;
}

int main()
{
    Animal a_= createAnimal();
    a_.speak();
    return 0;
}

我得到了输出:

Animal created                                                         
My name is: Bertia
Animal destroyed

这里调用的"动物创建"构造函数是针对哪个对象 a 或 a_ 以及析构函数。它是在我们定义动物 a 的地方调用还是何时调用我们调用 createAnimal(( 对于 a_ 析构函数也是如此,什么时候在 main 函数结束后调用 a_ 或在 createAnimal(( 函数结束后

调用它?

现在我的问题是构造函数的"动物创建"是针对哪个对象 a 或 a_,析构函数也是针对哪个对象 a 或 a_?

双。这里不需要两个对象。

并且请解释如何创建此处的对象的过程以及复制构造函数的机制是否适用,即如何调用和销毁对象。

该对象在createAnimal中创建并返回到 main ,在那里它变得a_ 。不需要副本构造,因为它可以通过延长临时的生存期来省略。

C++ 标准特别允许这种优化,这是允许优化以更改正确代码行为的罕见情况之一。

您可以添加更多 cout 来找出答案。 例如,像这样:

Animal createAnimal()
{
    std::cout << " creation of a " << std::endl;
    Animal a;
    a.setName("Bertia");
    std::cout << " returning from createAnimal " << std::endl;
    return a;        
}

int main()
{
   std::cout << " calling createAnimal() " << std::endl; 
   Animal a_= createAnimal();
   std::cout << " calling a_.speak() " << std::endl;
   a_.speak();
   std::cout << " returning from main " << std::endl;
   return 0;

}