c++之构造函数隐式调用

#include "stdafx.h"
#include <string.h>
#include <iostream>
using namespace std;

class Student {
private:
	char name[20];
	double score;
public:
	Student(const char* name);
	Student(const char* name, double score);
	void introduce();
};

Student::Student(const char* name)
{
	strncpy(this->name, name, 20);
}

Student::Student(const char* name, double score)
	:score(score)
{
	strncpy(this->name,name,20);
}

void Student::introduce()
{
	cout << "name:" << name << ",score:" << score << endl;
}

int main()
{
	/*
	//通过运算符"->"访问对象里的公有(public)成员
	Student stu("Tom", 99);
	Student* pStu;
	pStu = &stu;
	pStu->introduce();*/

	Student stu = "Tom";
	stu.introduce();
    return 0;
}

此时执行的结果:

会发现没有初始化score,score相当于一个乱码,此时会出现构造函数的隐式调用的情况。

防止构造函数隐式调用 , 只要在构造函数的声明里(11行)加上explicit就行,即 explicit Student(const char* name); 此时再执行就会报错了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值