#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); 此时再执行就会报错了。