In my current lab, we are supposed to learning about constructors,classes, utili
ID: 2247861 • Letter: I
Question
In my current lab, we are supposed to learning about constructors,classes, utilizing private and public, and how to use git in linux. The assignment is to gather grades and find the average by student name. The problem is when I give the class the name in the main function it gives me this error: conversion from ‘const char [18]’ to non-scalar type Student’ requested. I feel like I followed the instructions given well so i dont know what Im doing wrong. Can you please help me?!
MY CODE:
#include <iostream>
using namespace std;
class Student
{
public:
Student(string name)
{
student_name = name;
}
string name()
{
return student_name;
}
void exam(double grade)
{
exam_sum += grade;
exam_num_grades++;
}
double average()
{
return exam_sum / exam_num_grades;
}
private:
string student_name;
double exam_sum = 0;
double exam_num_grades = 0;
};
int main(void)
{
Student student = "Bjarne Stroustrup";
}
Explanation / Answer
The modified code is as follows:
Errors are observed regarding initialization of exam_sum and exam_num_grades and the error as mentioned in the question.
For the error mentioned in the question, instead of assigining "Bjarne Stroustrup" directly to th object, now it has been done through a string object.
Initilization errors have been avoided with intializing them in the constructor.
#include <iostream>
using namespace std;
class Student
{
public:
Student(string name)
{
student_name = name;
exam_sum = 0;
exam_num_grades = 0;
}
string name()
{
return student_name;
}
void exam(double grade)
{
exam_sum += grade;
exam_num_grades++;
}
double average()
{
return exam_sum / exam_num_grades;
}
private:
string student_name;
double exam_sum;
double exam_num_grades;
};
int main(void)
{
string s = "Bjarne Stroustrup";
Student student = s;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.