c ++类指针与类对象转化_在C ++中的另一个类声明中创建一个类的对象

c ++类指针与类对象转化

As we know that a class contains data members and member function, and an object can also be a data member for another class.

我们知道一个类包含数据成员和成员函数 ,而一个对象也可以是另一个类的数据成员。

Here, in the given program, we are doing the same. We have a class named Marks that contains two data members rno - to store roll number and perc - to store the percentage of the student. We have another class named Students that contains two members name - to store the name of the student and objM - which is an object of Marks class.

在这里,在给定的程序中,我们正在做同样的事情。 我们有一个名为类商标 ,其中包含两个数据成员RNO -存储卷号和PERC -存储学生的百分比。 我们还有另一个名为“ 学生”的类,其中包含两个成员名称 -用于存储学生的名称和objM-这是Marks类的对象。

In Students class there are two member functions:

在学生类中,有两个成员函数:

  1. readStudent() - To read the name of the student, and Here, we called readMarks() member function of Marks class by using objM - it will read roll number and percentage.

    readStudent() -要读取学生的姓名,在这里,我们使用objM调用了Marks类的readMarks()成员函数-它会读取卷数和百分比。

  2. printStudent() - To print the name of the student, and Here, we called printMarks() member function of Marks class by using objM - it will print roll number and percentage.

    printStudent() -要打印学生的姓名,在这里,我们使用objM调用了Marks类的printMarks()成员函数-它会打印卷数和百分比。

Program:

程序:

#include <iostream>
#include <string.h>

using namespace std;

class Marks
{
	private:
		int rno;
		float perc;
	
	public:
		//constructor
		Marks()
		{rno = 0; perc = 0.0f;}
		
		//input roll numbers and percentage
		void readMarks(void)
		{
			cout<<"Enter roll number: ";
			cin>>rno;
			cout<<"Enter percentage: ";
			cin>>perc;
		}
		
		//print roll number and percentage
		void printMarks(void)
		{
			cout<<"Roll No.: "<<rno<<endl;
			cout<<"Percentage: "<<perc<<"%"<<endl;
		}
};

class Student
{
	private:
		//object to Marks class
		Marks objM;
		char name[30];
	
	public:
		//input student details
		void readStudent(void)
		{
			//Input name
			cout<<"Enter name: ";
			cin.getline(name, 30);
			//input Marks
			objM.readMarks();			
		}
		
		//print student details
		void printStudent(void)
		{
			//print name
			cout<<"Name: "<<name<<endl;
			//print marks
			objM.printMarks();
		}
};

//main code
int main()
{
	//create object to student class
	Student std;
	std.readStudent();
	std.printStudent();
	
	return 0;
}

Output

输出量

Enter name: Amit Shukla
Enter roll number: 101
Enter percentage: 84.02
Name: Amit Shukla
Roll No.: 101
Percentage: 84.02%


翻译自: https://www.includehelp.com/cpp-programs/create-an-object-of-a-class-inside-another-class-declaration.aspx

c ++类指针与类对象转化

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值