构造函数参数默认值编译失败_在C ++中使用默认,参数化和复制构造函数设置数据成员的值...

构造函数参数默认值编译失败

Create a class and set values to the private data members using a default, parameterized and copy constructor in C++.

使用C ++中的默认,参数化和复制构造函数创建一个类并为私有数据成员设置值

This is an example of C++ constructors, here we have a class named person and private data members name and age. In this example, we will set values to name and age through the default, parameterized and copy constructors.

这是C ++构造函数的示例,这里有一个名为person的类,私有数据成员name和age 。 在此示例中,我们将通过默认,参数化和复制构造函数将值设置为name和age 。

Here, we will create three objects p1, p2 and p3. p1 will be initialized with a default constructor, p2 will be initialized with a parameterized constructor and p3 will be initialized with the copy constructor.

在这里,我们将创建三个对象p1 , p2和p3 。 p1将使用默认构造函数初始化, p2将使用参数化构造函数初始化, p3将使用复制构造函数初始化。

Program:

程序:

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

class person{
	private:
		char name[30];
		int age;
	
	public:
		//default constructor
		person(){
			strcpy(name,"None");
			age = 0;
		}
		//parameterized constructor
		person(char n[], int a){
			strcpy(name, n);
			age = a;
		}
		//copy constructor
		person(person &p){
			strcpy(name, p.name);
			age =p.age;
		}
		//function to display person details
		void print(void){
			cout<<name<<" is "<<age<<" years old."<<endl;
		}
};

//Main function
int main(){
	//creating objects
	person p1; //default constructor will be called
	person p2("Amit Shukla",21); //parameterized constructor will be called
	person p3(p2); //copy constructor will be called
	
	//printing
	cout<<"object p1..."<<endl;
	p1.print();
	cout<<"object p2..."<<endl;
	p2.print();	
	cout<<"object p3..."<<endl;
	p3.print();	
	
	return 0;
}

Output

输出量

object p1...
None is 0 years old.
object p2...
Amit Shukla is 21 years old.
object p3...
Amit Shukla is 21 years old.


翻译自: https://www.includehelp.com/cpp-programs/set-values-of-data-members-using-default-parameterized-and-copy-constructor.aspx

构造函数参数默认值编译失败

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值