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:
在学生类中,有两个成员函数:
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()成员函数-它会读取卷数和百分比。
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%
c ++类指针与类对象转化