So I have my header and my CPP for that class. My understanding is that although StudentID is a private variable in StudentClass.h I assign it to
StudentID = FullStudentID; under my set statement so it should work. Hoewever, I get error C2065: 'firstName': undeclared identifier. Tried all solutions I found but none work.
Am I setting up these variables incorrectly? I tried to have the variables as protected rather than private but same issue.
Header
#define Student_H
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
void SetStudentID(int FullStudentID);
void SetAge(int ageInYears);
void SetFirstName(string firstAName);
void SetLastName(string lastAName);
void SetEmail(string aEmailAddress);
int GetStudentID() const;
int GetAge() const;
string GetFirstName() const;
string GetLastName() const;
string GetEmail() const;
private:
int studentID;
int age;
string firstName;
string lastName;
string emailAddress;
};
#endif
Source
#include "StudentClass.h"
#include <iostream>
#include <string>
using namespace std;
void Student::SetStudentID(int FullStudentID) {
studentID = FullStudentID;
return;
}
void Student::SetAge(int ageInYears) {
age = ageInYears;
return;
}
void Student::SetFirstName(string firstAName) {
firstName = firstAName;
return;
}
void Student::SetLastName(string lastAName) {
lastName = lastAName;
return;
}
void Student::SetEmail(string aEmailAddress) {
emailAddress = aEmailAddress;
return;
}
//start of get statements -------------------------------------------------------------------
int Student::GetStudentID() const {
return;
}
int Student::GetAge() const {
return;
}
string Student::GetFirstName()const {
return;
}
string Student::GetLastName()const {
return;
}
string Student::GetEmail()const {
return;
}
void StudentPrint() const {
cout << "student ID: " << studentID << endl;
cout << "age: " << age << endl;
cout << "First name: " << firstName << endl;
cout << "Last name: " << lastName << endl;
cout << "Email: " << emailAddress << endl;
}
StudentPrint is not a member function of Student and can thus not access those variables. Either make it a member function of Student, or better yet, use the 'get' functions you've defined (after you've actually implemented them).
void StudentPrint(const Student& student) {
cout << "student ID: " << student.GetStudentID() << endl;
cout << "age: " << student.GetAge() << endl;
cout << "First name: " << student.GetFirstName() << endl;
cout << "Last name: " << student.GetLastName() << endl;
cout << "Email: " << student.GetEmailAddress() << endl;
}
As a side note; StudentPrint cannot be marked as const as it's not a member function, but a free function. Only member functions can be marked as const.
Not sure how to mark a selection as the fix but
"How is StudentPrint supposed to print a student's information? Either make it a member function, or pass in a Student object as a parameter. – cigien 8 mins ago"
Called it. I forgot to include the print as a member function. Now I'm getting declaration errors but I'll try to sort that out my self and post a new question if it comes up. Thanks everyone you're awesome!
Related
This question already has answers here:
Undefined reference to static variable c++
(3 answers)
Closed 2 years ago.
I created a Class Student with instance data members
like studentname, studentaddress, studentrollno
i declared private static data member CollegeName that could be shared among all instances of class.
used promptfunction to take user input from the console
next functions to display student details.
Meanwhile resulting in below errors :
Meanwhile codes goes here:
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
int studentrollno;
string studentName;
string studentAddress;
static string CollegeName;
public:
void setRollNo(int rollno) {
studentrollno = rollno;
}
int getRollNo() {
return studentrollno;
}
void setName(string name) {
studentName = name;
}
string getName() {
return studentName;
}
void setAddress(string address) {
studentAddress = address;
}
string getAddress() {
return studentAddress;
}
static void setCollegeName(string collegename) {
CollegeName = collegename;
}
static string getCollegeName() {
return CollegeName;
}
void displayStudentDetails(); // member functions declare inside class Meanwhile it is defined
outside
static void show() {
cout << "this is static function " << endl;
}
};
// member functions define outside Student class
void Student :: displayStudentDetails() {
cout << "Student Name : " << getName() << " Student RollNo : " << getRollNo() << "Student Address
: " << getAddress() << "CollegeName: "<< getCollegeName() << endl;
}
void promptValues(Student &student) {
cout << "Enter the student Details " << endl;
cout << "Enter the details about student objects " << endl;
cout << endl;
int studentrollno;
string studentname , studentaddress ;
string collegename;
cout << "Enter the RollNo of the student " << endl;
cin >> studentrollno;
cout << "Enter the Name of the student " << endl;
cin >> studentname;
cout << endl;
cout << "Enter the address of the student " << endl;
cin >> studentaddress;
cout << endl;
cout << "Enter the collegeName of the student " << endl;
cin >> collegename;
student.setRollNo(studentrollno), student.setName(studentname), student.setAddress(studentaddress),
student.setCollegeName(collegename);
}
int main() {
Student student1, student2 , student3 , student4 , student5 ;
Student studentarrays[5] = { student1, student2, student3, student4, student5 };
Student studentmodel[5];
for (int i = 0; i < 5; i++) {
Student model;
model = studentarrays[i];
promptValues(model);
studentmodel[i] = model;
}
for (Student studentdetails : studentmodel) {
studentdetails.displayStudentDetails();
}
Student::show();
return 0;
}
You have omited the definition of the static member Student::CollegeName. It is only declared in the class, now you should define it after the class declaration with this:
std::string Student::CollegeName;
For more information see https://en.cppreference.com/w/cpp/language/static
I'm having a problem understanding vectors of pointers to class objects, I tried a test code to try and understand it but whenever I enter a name and try to output it, it prints out numbers instead of the actual name that I entered. I'm hoping someone can explain this to me as I'm new to these concepts.
Also
Pets[0]->print(); dosent print at all while:
cout << "in main: " << Pets[0] << endl;
prints.
class Pet
{
public:
string name;
Pet(const string&);
string getName() const
{
return name;
}
void setName(const string& Name)
{
name = Name;
}
void print()const;
}
int main()
{
vector<Pet*> Pets;
string names;
int done = NULL;
do
{
{
cout << "Name: ";
cin >> names;
Pets.push_back(new Pet(names));
cin.ignore();
}
cout << "Add another ?" << endl;
cin >> done;
} while (done != 0);
Pets[0]->print();
cout << "in main: " << Pets[0] << endl;
system("pause");
}
Pet::Pet(const string& Name)
{
}
void Pet::print()const
{
cout << "Name: " << name;
}
The constructor of Pet does not assign the parameter, hence it remains empty.
Write...
Pet::Pet(const string& Name) : name(Name) { }
to do this initialization.
#include <iostream>
#include <string>
using namespace std;
// your code
class Dog {
public:
int age;
string name, race, voice;
Dog(int new_age,string new_name,string new_race,string new_voice);
void PrintInformation();
void Bark();
};
Dog::Dog(int new_age,string new_name,string new_race,string new_voice) {
age = new_age;
name = new_name;
race = new_race;
voice = new_voice;
}
void Dog::PrintInformation() {
cout << "Name: " << name;
cout << "\nAge: " << age;
cout << "\nRace: " << race << endl;
}
void Dog::Bark(){
cout << voice << endl;
}
int main()
{
Dog buffy(2, "Buffy", "Bulldog", "Hau!!!");
buffy.PrintInformation();
cout << "Dog says: " << buffy.Bark();
}
I'm newbie in C++ and I'm unable to figure out the error.I am getting the error at buffy.Bark(),it seems like its unable to print something which returns void.
no match for operator<< in std::operator<< >(&std::cout),((const char)
Either declare member function Bark like
std::string Dog::Bark(){
return voice;
}
and call it like
cout << "Dog says: " << buffy.Bark() << endl;
Or do not change the function but call it like
cout << "Dog says: ";
buffy.Bark();
because the function has return type void.
Or take another dog from the dog kennel.:)
Bark is defined as a void function:
void Dog::Bark(){
cout << voice << endl;
}
This means that trying to do cout << buffy.Bark() in main is trying to cout a void type variable, which is not possible. It's likely you simply meant buffy.Bark();, which will already output for you.
Ok so i'm fairly new to c++ and this is my first try using vectors. My goal is to store objects into a vector. I'm trying to follow this youtube tutorial:
http://www.youtube.com/watch?v=iPlW5tSUOUM
and i think mine is pretty much the same apart from his runs.
I just keep getting errors and it won't run. Any help would be appreciated :)
Maybe it's something small, but i've been checking for a while now and i can't see anything.
Errors:
1>c:\users\user\desktop\vector objects c++\testvectorobjects\testvectorobjects\main.cpp(61): error C3867: 'Employees::getSalary': function call missing argument list; use '&Employees::getSalary' to create a pointer to member
1>c:\users\user\desktop\vector objects c++\testvectorobjects\testvectorobjects\main.cpp(61): error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'overloaded-function' (or there is no acceptable conversion)
1>c:\program files (x86)\microsoft visual studio 11.0\vc\include\ostream(695): could be 'std::basic_ostream<_Elem,_Traits> &std::operator <<>(std::basic_ostream<_Elem,_Traits> &,const char *)'
I have 3 files: main.cpp, Employee.h, Employees.cpp
//main.cpp
#include <iostream>
#include <string>
#include <vector>
#include "Employee.h"
void fillVector(vector<Employees>&);
//fill vector - fills in Employee Info
//vector<Employees>& - Employees at the station
void printVector(const vector<Employees>&);
//print vector - prints the employee info
//const vector<Employees>& - employees at the station
using namespace std;
vector<Employees> Staff;
int main(){
fillVector(Staff);
printVector(Staff);
}
//filling the employee vector
void fillVector(vector<Employees> & newStaff){
int id;
double salary;
string name;
cout << "Number of Employees" << endl;
int amountEmployees;
cin >> amountEmployees;
for (int i = 0; i < amountEmployees; i++) {
cout << "Enter Employee Id: ";
cin >> id;
cout << "Enter Employee Salary: ";
cin >> salary;
cout << "Enter Employee Name: ";
cin >> name;
Employees newEmployees(id, salary, name);
newStaff.push_back(newEmployees);
cout << endl;
}
cout << endl;
}
//printing the employee vector
void printVector(const vector<Employees>& newStaff){
unsigned int size = newStaff.size();
for (unsigned int i = 0; i < size; i++) {
cout << "Employee Id: " << newStaff[i].getID << endl;
cout << "Employee Name: " << newStaff[i].getName << end;
cout << "Employee Salary: " << newStaff[i].getSalary << end;
cout << endl;
}
}
//Employee.h
//Header
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <iostream>
#include <string>
using namespace std;
class Employees{
public:
//after
//Default Constructor
Employees();
//Overload constructor
Employees(int, double, string);
//Destructor
~Employees();
//Accessor Functions
int getID() const;
//getId
//return int - Id for Employee
double getSalary() const;
//getSalary
//return salary - salary of Employee
string getName() const;
//getName
//return name - Name of Employee
//Mutators
void setId(int);
//setId - for Employee
void setSalary(double);
//setSalary - for Employee
void setName(string);
//setName - for Employee
//
//before
//ID
//void setEmployeeId(int a){
//employeeId = a;
//}
////Salary
//void setSalary(double b){
//salary = b;
//}
////Name
//void setName(string c){
//name = c;
//}
private:
//after
//before
int employeeId; //id
double employeeSalary; //salary
string employeeName; //name
};
#endif
//Employees.cpp
#include "Employee.h"
Employees::Employees() {
employeeName = ' ';
}
Employees::Employees(int id, double salary, string name){
employeeId = id;
employeeSalary = salary;
employeeName = name;
}
Employees::~Employees(){
}
int Employees::getID()const{
return employeeId;
}
double Employees::getSalary()const{
return employeeSalary;
}
string Employees::getName()const{
return employeeName;
}
void Employees::setId(int id){
employeeId = id;
}
void Employees::setSalary(double salary){
employeeSalary = salary;
}
void Employees::setName(string name){
employeeName = name;
}
'Employees::getSalary': function call missing argument list;
That seems quite clear: getSalary is a function, and you need an argument list when you call a function:
cout << "Employee Salary: " << newStaff[i].getSalary() << endl;
^^ ^
and similarly for the calls to getID and getName.
Fixing that should also fix the second error; or that might be caused by the mistyping of endl.
I think the error is pretty self explaining, once you know a bit of C++ terms. The second part (use '&Employees::getSalary' to create a pointer to member) will actually confuse you, because the compiler it talking about a totally unrelated C++ capability, that it thinks you may be trying to use.
Let's see:
'Employees::getSalary': function call missing argument list
To call a function, you have to specify the argument list, with parenthesis, even if you have no arguments at all!
cout << "Employee Salary: " << newStaff[i].getSalary() << end;
That is, add a few () here and there.
You have to use function call operator () (application operator) to call a function
function_name() // call a function named function_name
thus:
cout << "Employee Id: " << newStaff[i].getID() << endl;
^^
cout << "Employee Name: " << newStaff[i].getName() << end;
^^
cout << "Employee Salary: " << newStaff[i].getSalary() << end;
^^
This:
newStaff[i].getName
Needs to be this:
newStaff[i].getName()
And so on.
this is the header file: employee.h
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <iostream>
#include <string>
using namespace std;
class Employee {
public:
Employee(const string &first, const string &last)
Overloaded Constructor
: firstName(first),
firstName overloaded constructor
lastName(last)
lastName overloaded constructor
{ //The constructor start
++counter;
it adds one plus per each object created;
cout << "Employee constructor for " << firstName
<< ' ' << lastName << " called." << endl;
}
~Employee() {
Destructor
cout << "~Employee() called for " << firstName << ' '
<< lastName << endl;
Returns the first and last name of each object
--counter;
Counter minus one
}
string getFirstName() const {
return firstName;
}
string getLastName() const {
return lastName;
}
static int getCount() {
return counter;
}
private:
string firstName;
string lastName;
static int counter = 0;
Here is where i got the error. But, why?
};
principal program: employee2.cpp
#include <iostream>
#include "employee2.h"
using namespace std;
int main()
{
cout << "Number of employees before instantiation of any objects is "
<< Employee::getCount() << endl;
Here ir call te counter's value from the class
{
Start a new scope block
Employee e1("Susan", "Bkaer");
Initialize the e1 object from Employee class
Employee e2("Robert", "Jones");
Initialize the e2 object from Employee class
cout << "Number of employees after objects are instantiated is"
<< Employee::getCount();
cout << "\n\nEmployee 1: " << e1.getFirstName() << " " << e1.getLastName()
<< "\nEmployee 2: " << e2.getFirstName() << " " << e2.getLastName()
<< "\n\n";
}
end the scope block
cout << "\nNUmber of employees after objects are deleted is "
<< Employee::getCount() << endl; //shows the counter's value
} //End of Main
What is the problem?
I have no idea what's wrong.
I have been thinking a lot, but a i do not what is wrong.
The initialization of the static member counter must not be in the header file.
Change the line in the header file to
static int counter;
And add the following line to your employee.cpp:
int Employee::counter = 0;
Reason is that putting such an initialization in the header file would duplicate the initialization code in every place where the header is included.
According to a similar SO answer there is another approach, in particular suited for your current implementation (header-only library):
// file "Employee.h"
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
class Employee {
public:
Employee() {
getCounter()++;
}
~Employee() {
getCounter()--;
}
static auto getCount() -> std::size_t {
return getCounter();
}
private:
// replace counter static field in class context,
// with counter static variable in function context
static auto getCounter() -> std::size_t& {
static std::size_t counter = 0;
return counter;
}
};
#endif //EMPLOYEE_H
I took the liberty to use std::size for representing the non-negative employee count and trailing return syntax for functions.
Accompanying test (ideone link):
#include "Employee.h"
int main() {
std::cout << "Initial employee count = " << Employee::getCount() << std::endl;
// printed "count = 0"
Employee emp1 {};
std::cout << "Count after an employee created = " << Employee::getCount() << std::endl;
// printed "count = 1"
{
Employee emp2 {};
std::cout << "Count after another employee created = " << Employee::getCount() << std::endl;
// printed "count = 2"
}
std::cout << "Count after an employee removed = " << Employee::getCount() << std::endl;
// printed "count = 1"
return 0;
}