0
点赞
收藏
分享

微信扫一扫

C++(11):自定义字面量构造对象

程序员阿狸 2022-04-21 阅读 57
c++

C++11支持了可以像string str = "hello world",从而以更直观的方式来构造对象:

#include <iostream>
using namespace std;

class Weight{
public:
	Weight(unsigned int kg):m_kg(kg){}
	unsigned int m_kg;
};

ostream& operator<<(ostream& out, const Weight& w)    //定义对象的输出函数
{
	out<<"Weight is "<<w.m_kg<< " KG"<<endl;
	return out;
}

Weight operator"" _KG(unsigned long long v)           //通过_KG定义一个字面量转换函数,返回对象
{
	return Weight(v);
}

int main(){

	Weight&& w = 20_KG;    //右值引用到字面量转换函数返回的临时对象
	cout<<w;               //输出:Weight is 20 KG
	return 0;
}
举报

相关推荐

0 条评论