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

C++ 中,调用构造函数是指在某些情况下,编译器会自动调用构造函数来创建一个对象,而不需要程序员显调用构造函数。 例如,当我们定义一个类的对象时,编译器会自动调用该类的默认构造函数来创建对象。又例如,当我们用一个已有的对象初始化另一个对象时,编译器也会自动调用该类的拷贝构造函数来完成初始化。 下面是一个示例代码,演示了调用构造函数的情况: ```c++ #include <iostream> using namespace std; class MyClass { public: int value; MyClass() { // 默认构造函数 cout << "default constructor called" << endl; value = 0; } MyClass(int n) { // 带参数的构造函数 cout << "constructor with int called" << endl; value = n; } MyClass(const MyClass& other) { // 拷贝构造函数 cout << "copy constructor called" << endl; value = other.value; } }; int main() { MyClass a; // 调用默认构造函数 MyClass b = 10; // 调用带参数的构造函数 MyClass c(a); // 调用拷贝构造函数 MyClass d = b; // 调用拷贝构造函数 return 0; } ``` 在上面的代码中,当我们定义对象 `a` 时,编译器会自动调用 `MyClass` 类的默认构造函数;当我们定义对象 `b` 时,由于使用了整数 `10` 进行初始化,编译器会自动调用 `MyClass` 类的带参数的构造函数;当我们定义对象 `c` 和 `d` 时,由于使用了已有的对象进行初始化,编译器会自动调用 `MyClass` 类的拷贝构造函数。 需要注意的是,当我们使用 `explicit` 关键字修饰一个构造函数时,就不能进行调用构造函数了,只能使用显调用构造函数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值