C++完全是新手
C++ dought completely Novice
#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;
}
相关文章:
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 我是c ++的新手,你能解释一下在这种情况下的指针吗
- 我是 c++ 的新手.学习基本知识后,我想做井字游戏.对于印刷板,我在下面写代码,但它显示错误
- 我是编程新手
- C++新手,想知道如何使用VS code 2019播放音频文件
- C++功能泄漏内存,我是C++新手,不确定如何解决
- 如何正确解析子字符串,以便它们对我的新手计算器有效?
- 我是C++新手,我想知道,为什么在c ++中使用纯虚函数?为什么要使用纯虚函数?
- 结构新手,我对如何从 void 函数中返回值并将其放入另一个函数感到困惑
- 如何在使用 ItemType 的模板类时将新节点插入二叉树 c++.(我是 c++ 的新手)
- 我是 C++ 的新手,我试图调用 make 一个以 2 个类作为其参数的类构造函数
- 作为一个C++新手,我遇到了麻烦
- 如何一步一步地正确解释此代码?(编程新手)
- 什么是"MFC Dialog Extension"?(Windows/C++ 新手 - Linux 背景)
- 我是 c++ 的新手,有没有一种算法可以找到 3d 数组中最接近的 0 的距离?
- C++浮点数与双胞胎设置精度奇数(新手)
- C++新手的类成员函数
- 编码新手需要有关 if 语句的帮助
- 我是 c++ 编程的新手,我一直在做以下任务:
- C++的新手试图弄清楚类约定