#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.
Related
I'm still learning C++ so go easy on me.
Is there a way I can pass an object to a method without specifying an object? I'm probably butchering the terms so ill show code.
class Student
{private:
std::string Name;
float GPA;
char Sex;
int Absentee;
int *Data ;
public:
std::string GetName();
float GetGPA();
char GetSex();
int GetAbsentee();
void SetData(int);
int GetData();
int *GetDataAddr();
//Methods
void DisplayStudent(Student);
void Student::DisplayStudent(Student Stud)
{
std::cout << "___________________________________" << std::endl;
std::cout << "Name :" << Stud.GetName() << std::endl;
std::cout << "GPA :" << Stud.GetGPA() << std::endl;
std::cout << "Sex :" << Stud.GetSex() << std::endl;
std::cout << "Absentee :" << Stud.GetAbsentee() << std::endl;
std::cout << "Data :" << Stud.GetData() << std::endl;
std::cout << "Data Add :" << Stud.GetDataAddr() << std::endl;
std::cout << "___________________________________" << std::endl;
}
int main() {
Student Spike("Spike", 3.9f, 'M', 43,55);
* Compiles fine: Spike.DisplayStudent(Spike);
* DOSNT Compile: Student DisplayStudent(Spike);
* C++ a nonstatic member reference must be relative to a specific object*
return 0;
}
So the question I have is at least with this method, why do I need to specify or rather, what is the purpose of "Spike" in "Spike.DisplayStudent(.....)"? Student::Display(.....) makes far more sense to me.
If your Student::DisplayStudent is designed to display information for the student who is represented by that class instance, you don't need to pass Student Stud at all, just use member variables.
If however it is designed to display info for ANY student - you can make it a static member, or a free-standing function.
If you want the member function DisplayStudent to display the information for the very instance of Student on which the function is called, you do not need to pass a Student as an argument.
class Student {
public:
// The getter methods should be `const`, since calling them does not change
// the `Student`:
const std::string& GetName() const; // return a `const&` to avoid unecessary copying
void DisplayStudent() const; // No `Student` argument, like in `GetName()`
// ...
};
void Student::DisplayStudent() const {
std::cout << "___________________________________\n"
"Name :" << GetName() << "\n"
"GPA :" << GetGPA() << "\n"
"Sex :" << GetSex() << "\n"
"Absentee :" << GetAbsentee() << "\n"
"Data :" << GetData() << "\n"
"Data Add :" << GetDataAddr() << "\n"
"___________________________________\n";
}
You also do not need to call getter methods in DisplayStudent() since you have access to the private member variables and do not need to do any calculations before returning the result.
Usage example (if the appropriate constructor exists as you've indicated):
int main() {
Student Spike("Spike", 3.9f, 'M', 43,55);
Spike.DisplayStudent(); // no instance passed as an argument
}
Context
My professor gave me a task to make a program using aggregation between 2 classes while also separating the classes into a .h and .cpp files.
My solution
The header file containing the class declaration:
#include <iostream>
#include <string>
using namespace std;
class medicalCompany {
private:
string ceoName;
string email;
string phoneNumber;
string locate;
public:
medicalCompany();
void Name(string n);
void mail(string m);
void phone(string p);
void location(string l);
~medicalCompany();
};
class origin {
private:
medicalCompany country;
public:
origin();
void address();
~origin();
};
and my .cpp file:
#include <iostream>
#include "function.h"
#include <string>
using namespace std;
medicalCompany::medicalCompany() {
cout << "OUR COMPANY IS GLAD TO BE OF SERVICE !" << endl;
cout << "****************************************************" << endl;
}
void medicalCompany::Name(string n){
ceoName = n;
cout << "OUR CEO IS " << endl;
cout<< ceoName << endl;
cout << "****************************************************" << endl;
}
void medicalCompany::mail(string m) {
email = m;
cout << "USE OUR EMAIL TO CONTACT US : " << endl;
cout<< email << endl;
cout << "****************************************************" << endl;
}
void medicalCompany::phone(string p) {
phoneNumber = p;
cout << "THIS IS OUR CUSTOMER SERVICE PHONE NUMBER " << endl;
cout<< phoneNumber << endl;
cout << "****************************************************" << endl;
}
void medicalCompany::location(string l) {
locate = l;
cout << " OUR COMPANY IS LOCATED IN " << endl;
cout << locate << endl;
cout << "****************************************************" << endl;
}
medicalCompany::~medicalCompany() {
cout << "thanks for trusting our company ^_^" << endl;
cout << "****************************************************" << endl;
}
origin::origin() {
cout<< "constructor 2"<<endl;
}
void origin::address() {
cout << country.location;
}
origin::~origin() {
cout << "bye" << endl;
}
The two classes are used in my main.cpp file:
#include <iostream>
#include <string>
#include "function.h"
using namespace std;
int main() {
medicalCompany o;
o.Name("jack");
o.mail("ouremail#company.com");
o.phone("2342352134");
o.location("Germany");
origin o2;
return 0;
}
Problem
I run into this error :
Severity Code Description Project File Line Suppression State
Error C3867 'medicalCompany::location': non-standard syntax; use '&' to create a pointer to member CP2_HW c:\function.cpp 41
You can either:
replace void origin::address(){cout << country.location;} by void origin::address(){country.location();}
or by void origin::address(){cout << country.locate;} if you put the locate member as a public variable.
Also, few remarks:
Generally you would prefer avoiding exposing private members, so the first solution should be prefered.
the instruction using namespace std; is usually considered bad practice, and should be avoided, as the cost of possible risks does not overweight the benefit of not having to type std::cout(see this question for more information)
In terms of naming convention, I would have exchanged the names of locate and location: location should be the member variable and locate the action (function) of getting the location.
Prefer using a constructor and intialization lists rather than getter/setter.
Your output formatting should be very separate from the logic of your classes, for example implementing a << operator for your class.
Following this logic, your code should look more like:
#include <iostream>
#include <string>
class medicalCompany {
private:
std::string _ceoName;
std::string _email;
std::string _phoneNumber;
std::string _location;
public:
// Constructor
medicalCompany(std::string name, std::string email, std::string phone, std::string location):
_ceoName(name),
_email(email),
_phoneNumber(phone),
_location(location)
{}
friend ostream& operator<<(ostream& os, const medicalCompany& dt);
};
and for the ostream operator:
ostream& operator<<(ostream& os, const medicalCompany& co)
{
os << co._ceoName << " " co._phoneNumber << ' ' << co._email;
return os;
}
This would allows to write code like this in your main:
int main() {
medicalCompany o("jack", "ouremail#company.com","2342352134","Germany")
std::cout << o << std::endl;
return 0;
}
The code is not functional and you would have to edit it to fit your formating requirement, but you have the idea :) Good luck!
So, I defined the method displayStudInfo in the 'Student' Class and called it in the main function. But I'm getting the error "Function not declared in this scope". Can anyone please tell me why this is happening and what I can do to solve this problem?
#include <iostream>
#include <string>
using namespace std;
class Student{
public:
int age;
string name;
void enterInfo(){
cout << "Enter your age = " ; cin >> age;
cout << "Enter your name = "; cin >> name;
}
void displayStudInfo(Student s)
{
cout << "Age = " << s.age << ", name=" << s.name << endl;
}
};
int main(){
int size;
Student stud[100];
Student abir;
abir.enterInfo();
displayStudInfo(abir);
}
In your case void displayStudInfo(Student s) is a member function of Student so you have to call it on an instance of Student, the same way you did with enterInfo.
You can solve that in different ways. One way is to make that member function a free function by moving it out of the body of the Student
class Student{
public:
// …
};
void displayStudInfo(Student s)
{
cout << "Age = " << s.age << ", name=" << s.name << endl;
}
int main(){
// …
displayStudInfo(abir);
}
displayStudInfo is, in fact, a good candidate for a free function. Or you make it static which is similar to a free function, and access the static member function using Student::displayStudInfo(abir).
The other way would be to call displayStudInfo on abir in that case you don't need the Student argument, as abir is implicitly passed to displayStudInfo.
class Student{
public:
// …
void displayStudInfo()
{
cout << "Age = " << age << ", name=" << name << endl;
}
};
int main(){
// …
abir.displayStudInfo();
}
void displayStudInfo(Student s) hidden in side class.
So, its not accessible in main().
Try:
void displayStudInfo()
{
cout << "Age = " << age << ", name=" << name << endl;
}
call in main():
abir.displayStudInfo();
In C++, all member functions implicitly receive a parameter which points to the current object. This parameter is the this pointer.
Therefore, it doesn't make sense for you to specify an additional (explicit) parameter for the object in your definition of the function displayStudInfo.
It would make sense to rewrite the function definition to
void displayStudInfo()
{
cout << "Age = " << age << ", name=" << name << endl;
}
and to call it with
abir.displayStudInfo();
instead of
displayStudInfo(abir);
Alternatively, you could make the function displayStudInfo a non-member function, by putting it outside the declaration of class Student. In that case, you would have to keep the explicit parameter, because that parameter is only passed implicitly to member functions.
I am in the middle of getting my feet wet with the use of composition & classes in C++. A code snippet I came across implements composition in the following manner:
#include<iostream>
using namespace std;
class Engine {
public:
int power;
};
class Car {
public:
Engine e;
string company;
string color;
void show_details() {
cout << "Compnay is: " << company << endl;
cout << "Color is: " << color << endl;
cout << "Engine horse power is: " << e.power << endl;
}
};
int main() {
Car c;
c.e.power = 500;
c.company = "hyundai";
c.color = "black";
c.show_details();
return 0;
}
This compiles fine, and runs. One thing I do not like about this implementation is the actual location of the function "void show_details", which I would prefer to place outside.
However, if I naively try to do the following:
#include<iostream>
using namespace std;
class Engine {
public:
int power;
};
class Car {
public:
//Engine e;
string company;
string color;
void show_details();
//void show_details() {
// cout << "Compnay is: " << company << endl;
// cout << "Color is: " << color << endl;
// cout << "Engine horse power is: " << e.power << endl;
//}
};
void Car::show_details(){
cout << "Compnay is: " << company << endl;
cout << "Color is: " << color << endl;
cout << "Engine horse power is: " << e.power << endl;
}
int main() {
Car c;
c.e.power = 500;
c.company = "hyundai";
c.color = "black";
c.show_details();
return 0;
}
g++ returns the following errors:
comp3.cpp: In member function ‘void Car::show_details()’:
comp3.cpp:22:44: error: ‘e’ was not declared in this scope
cout << "Engine horse power is: " << e.power << endl;
^
comp3.cpp: In function ‘int main()’:
comp3.cpp:26:9: error: ‘class Car’ has no member named ‘e’
c.e.power = 500;
I am clearly confused regarding issues of scoping, but I am not sure as to what the missing piece is.
Thanks for any & all help!!!
In the second example you commented out e.
//Engine e;
So I have these classes:
In main I wrote an array of pointers:
student *arry[10];
How can I make each cell point to an object of a different class?
For example :
I want the cell 0 , 2 , 4
point to an object of class medstudent
using ( new statement )
thank you
here is class medStudent
#include<iostream>
#include"student.cpp"
using namespace std;
class medStudent:public student {
public :int clinicH;
public:
medStudent(int ch, string n , int i ):student(n,i){
setClinicH(ch);
cout << "New Medecine Student" << endl;
}
~medStudent(){
cout << "Medecine Student Deleted" << endl;
}
medStudent(medStudent & ms):student(ms){
cout << "New Copy Medecined Student" << endl;
}
medstudent(){
}
void setClinicH(int ch){
clinicH = ch;
}
int getClinicH()const{
return clinicH;
}
void print()const{
student::print();
cout << "Clinical Hours: " << getClinicH() << endl;
}
};
Here is class student:
#include <iostream>
//#include"medstudent.cpp"
using namespace std;
class student//:public medstudent
{
public :
static int numberOfSaeeds;
const int id;
string name;
public:
~student(){
cout << "Delete Student: " << getName() << " " << endl ;
}
student(string n, int i):id(i){
setName(n);
cout << "Student with args" << endl ;
}
void setName(string n){
name = n;
}
string getName()const{
return name;
}
void print()const{
cout << "My name is: " << name << endl;
cout << "My ID is: " << id << endl;
}
void setNOS(int nos){
numberOfSaeeds = nos;
}
int getNOS(){
return numberOfSaeeds;
}
void printAddress()const{
cout << "My address is " << this << endl;
}
student * getAddress(){
return this;
}
student(student & sc):id(sc.id){
name = sc.name;
setName(sc.getName());
cout << "New Object using the copy constructor" << endl;
}
};
Here is main code:
#include<iostream>
using namespace std;
#include"time.cpp"
#include "student.cpp"
//#include"medstudent.cpp"
int main(){
student a1("asa" , 2);
student * a[10];
a[3]= new student("jj", 22 );
a[0] = new medStudent();
}
Since you explicitly declare a medStudent constructor the compiler will not create a default constructor for your class. And when you do new medStudent(); you are (explicitly) trying to invoke the default constructor, which doesn't exist.
That will give you a build error, one that should have been very easy to diagnose if you read it and most importantly shown it to us (when asking questions about build errors, always include the complete and unedited error output, including any informational output, in the body of the question, together with the code causing the error).
The solution? Call the existing parameterized constructor. E.g. new medStudent("foo", 123).
By the way, if you want inheritance to work okay, and the base-class destructor to be called when deleting an object of a child-class, then you need to make the destructors virtual.