Constructor Overloading in C++ - C++ 中的构造方法重载

Constructor Overloading in C++ - C++ 中的构造方法重载

1. Constructor Overloading in C++

Suppose we have a Student class and while making its object, we want to pass a name of it and if nothing is passed then the name should be unknown. And yes! we can do this by having two constructors.
假设我们有一个 Student 类,并且在创建它的对象时,我们想要传递它的名称,如果未传递任何内容,则该名称应为 unknown。是的!我们可以通过两个构造函数来实现。

//============================================================================
// Name        : std::class
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <string>

using namespace std;

class Student
{
	string name;
public:
	Student(string n)
	{
		name = n;
	}
	Student()
	{
		name = "unknown";
	}
	void printName()
	{
		cout << name << endl;
	}
};

int main()
{
	Student a("xyz");
	Student b;
	a.printName();
	b.printName();

	return 0;
}

Output

xyz
unknown

And it is working!

This is called constructor overloading.
这称为构造函数重载。

Now let’s understand this example. Here, we made two objects of class Student. While creating an object a, we passed a string "xyz" to the object as Student a( "xyz" );. This invoked the constructor having a string parameter Student( string n ).
现在让我们了解这个例子。在这里,我们创造了 Student 类的两个对象。在创建对象 a 时,我们向对象传递了一个字符串 "xyz" (Student a( "xyz" );)。这调用了具有字符串参数 Student( string n ) 的构造函数。

Similarly, while creating a second object b of the class Student, we didn’t pass anything to the object b as Student b;. So, the constructor having no parameter Student() got invoked and initialized the name with the value unknown.
同样,在创建 Student 类的第二个对象 b 时,我们没有将任何内容传递给对象 b (Student b;)。 因此,没有参数 Student() 的构造函数被调用并使用未知值初始化名称。

2. Condition for constructor overloading

The one condition for constructor overloading is that both the constructors must have different parameters. Like in the above example, in the first constructor, we passed one String and in the second, nothing.
构造函数重载的一个条件是两个构造函数必须具有不同的参数。就像上面的示例一样,在第一个构造函数中,我们传递了一个 String,而在第二个构造函数中,则没有传递任何内容。

We can’t make two constructors having exactly same arguments( e.g.- both having two ints ).
我们不能使两个构造函数具有完全相同的参数 (例如,都具有两个 ints)。

Either number of argument or type of argument must vary.
参数数量或参数类型必须有所不同。

We can have any number of constructors but with different arguments.
我们可以有任意数量的构造函数,但参数不同。

Don’t let your dreams be dreams.
不要让你的梦想成为梦想。

inheritance [ɪnˈherɪtəns]:n. 继承,遗传,遗产
class:类
derived class:继承类,派生类
subclass:子类
base class:基类
superclass:超类,父类
passion [ˈpæʃn]:n. 激情,热情,酷爱,盛怒
muscle [ˈmʌsl]:n. 肌肉,力量 vt. 加强,使劲搬动,使劲挤出 vi. 使劲行进

References

https://www.codesdope.com/cpp-initialization-list/

发布了473 篇原创文章 · 获赞 1762 · 访问量 104万+

猜你喜欢

转载自blog.csdn.net/chengyq116/article/details/104475966
今日推荐