构造函数是支持手动调用的

在阅读《C++ primer》的时候,注意到,构造函数是可以手动调用的。以前没有怎么留意这个问题。这里做个记录。

首先,手动调用构造函数系统实际上是创建了一个临时对象的,如果不保存这个临时对象,那么之后是无法使用这个对象的。

采用手动调用构造函数是一种初始化对象的方式,《C++ primer》中使用的情景是,当cin的数据不合法时就调用构造函数初始化一个默认的对象出来。

构造函数的手动调用的前提当然是这个构造函数是public控制的,因为构造函数是受访问控制符控制的。

下面是一个示例代码:

#include <iostream.h>
//using namespace std;

class Test{
public:
	Test(){value = 0;}
	Test(int v){value = v;}
	Test(const Test&){}
//	Test operator= (const Test&){ }
	~Test(){}
	friend ostream& operator<< (ostream &, const Test &);
	friend istream& operator>> (istream &, Test &);
//private:
	int value;
};

ostream& operator<< (ostream &out, const Test &test){
		out << "value = " << test.value << endl;
		return out; 
}

istream& operator>> (istream &in, Test &test){
	cout << "input value:";
	in >> test.value;
	return in;
}

void main()
{
	Test test = Test();
	cin >> test;
	test = Test(112);
	cout << test << endl;
}


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值