在C++中的模板对象期间调用的构造函数和击曲线如何调用。
您能解释一下如何调用构造函数和驱动器,因为当我看到Tempravary对象的输出4时,称为More Times Optive
项目args构造函数称为1
1 100
项目args构造函数称为2
2 afffections
项目args构造函数称为4
项目args构造函数称为3
项目desconstructor称为4
3 4教授
项目desconstructor称为4
项目desconstructor称为4
项目desconstructor称为3
项目desconstructor称为4
项目desconstructor称为2
项目desconstructor称为1
#include<iostream>
#include<string>
using namespace std;
template <typename template_type>
class item
{
string name;
template_type value;
public:
item(string name, template_type value)
:name{name}, value{value}
{
cout<<"item Args constructor called "<<name<<endl;
}
~item()
{
cout<<"item desconstructor called "<<name<<endl;
}
string get_name()const
{
return name;
}
template_type get_value()const
{
return value;
}
};
int main()
{
item<int> item1{"1", 100 };
cout<<item1.get_name()<<" "<<item1.get_value()<<endl;
item<string> item2{"2", "Proffecessor" };
cout<<item2.get_name()<<" "<<item2.get_value()<<endl;
item<item<string>> item3{"3", {"4","Professor"}};
cout<<item3.get_name()<<" "
<<item3.get_value().get_name()<<" "
<<item3.get_value().get_value()<<endl;
}
Can you please explain how constructor and destructor is called,
Because when i see the output for tempravary object 4 destructor called more times
output
item Args constructor called 1
1 100
item Args constructor called 2
2 Proffecessor
item Args constructor called 4
item Args constructor called 3
item desconstructor called 4
3 4 Professor
item desconstructor called 4
item desconstructor called 4
item desconstructor called 3
item desconstructor called 4
item desconstructor called 2
item desconstructor called 1
#include<iostream>
#include<string>
using namespace std;
template <typename template_type>
class item
{
string name;
template_type value;
public:
item(string name, template_type value)
:name{name}, value{value}
{
cout<<"item Args constructor called "<<name<<endl;
}
~item()
{
cout<<"item desconstructor called "<<name<<endl;
}
string get_name()const
{
return name;
}
template_type get_value()const
{
return value;
}
};
int main()
{
item<int> item1{"1", 100 };
cout<<item1.get_name()<<" "<<item1.get_value()<<endl;
item<string> item2{"2", "Proffecessor" };
cout<<item2.get_name()<<" "<<item2.get_value()<<endl;
item<item<string>> item3{"3", {"4","Professor"}};
cout<<item3.get_name()<<" "
<<item3.get_value().get_name()<<" "
<<item3.get_value().get_value()<<endl;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您错过了复制构造函数。这就是为什么您会看到比构造函数更多的驱动器调用。您还可以使用此代码看到它。
输出
https://godbolt.org/z/xhwh9hgr6
You miss the copy constructor. That's why you see more destructor call than constructor. You can also see it with this code.
output
https://godbolt.org/z/xhWh9hGr6