I am trying to place objects in an array list and 3 errors popped up. I looked into the forums and there's a question similar to mine but I don't think it's applicable in my case.
Here's my code:
in test.cpp (main file)
#include <iostream>
#include "House.h"
using namespace std;
House HouseArray[2];
int main()
{
string toPrint;
House Kubo("Kubo", 2);
HouseArray[0] = Kubo;
toPrint = HouseArray[0].GetHouseName;
cout <<toPrint<< endl;
}
in House.cpp
#include "House.h"
#include <iostream>
House::House(string a, int h)
{
Name = a;
Health = h;
}
void House::DamageHouse(int d) {
Health -= d;
cout << "Your " << Name << " has " << Health << " left."<<endl;
}
int House::GetHouseHealth() {
return Health;
}
string House::GetHouseName() {
string returning = Name;
return returning;
}
House::~House()
{
}
in House.h
#include <string>
using namespace std;
class House
{
string Name;
int Health;
public:
House(string a, int h);
int GetHouseHealth();
void DamageHouse(int d);
string GetHouseName();
~House();
};
Errors:
Error C2512 'House': no appropriate default constructor available test.cpp in line 9
Error C3867 'House::GetHouseName': non-standard syntax; use '&' to
create a pointer to
member test.cpp in line 16
Error C2679 binary '=': no operator found which takes a right-hand
operand of type 'overloaded-function' (or there is no acceptable
conversion) test.cpp in line 16
You need a default constructor if you want to create an array like that: House HouseArray[2]; The compiler will need to know how to create an empty House so that the initial array can be initialised. Thus add something like the following to House.h
House() {
Name = "";
Health = 0;
}
To call a function on a class, you need to add the braces:
toPrint = HouseArray[0].GetHouseName();
I suspect that the above will solve this issue as well.
Related
The problem I'm having is when i try to set some of my class variables within an array of 3 class objects, I get an error stating that the variables required by the function are not declared within the scope of the main function.
I'm still new to classes and separating my interface from my implementation and I do find it to be confusing at times.
I have been looking at some other examples on this site and others and I can't figure out exactly what my issue is and how to fix it.
interface.h file:
#ifndef INTERFACE_H
#define INTERFACE_H
#include <iostream>
#include <string>
#include <fstream>
using namespace std; // I know this is a programming sin to include inside a header file but my textbook wants me to do it this way
class student
{
public:
student(); // class constructor
void setstudent(string studentName, string ID, string studentNumber, string diploma); // Function im using to set objects in array object
private:
string studentName;
string ID;
string studentNumber; // class variables
string diploma;
int averageMark;
string codes [5];
int marks [5];
};
#endif // INTERFACE_H
implementation.cpp file:
#include <iostream>
#include "interface.h"
using namespace std;
student::student()
{
studentName = "";
ID = "";
studentNumber = ""; // constructor to initialise all class variables
diploma = "";
averageMark = 0;
codes [5] = {"", "", "", "", ""};
marks [5] = {0, 0, 0, 0, 0};
}
void student::setstudent(string studentName, string ID, string studentNumber, string diploma) // function to set class variables
{
cout << "Please enter a student name" << endl;
cin.getline(studentName);
cout << "Please enter a unique student ID" << endl;
cin.getline(ID);
cout << "Please enter a unique student number" << endl;
cin.getline(studentNumber);
cout << "Please enter diploma name" << endl;
cin.getline(diploma)
if (diploma == "Garden Design")
{
codes[5] = {"G1","G2","G3","G4","G5"};
}
else if (diploma == "Gourmet Cooking")
{
codes[5] = {"C1","C2","C3","C4","C5"};
}
}
main.cpp file:
#include <iostream>
#include "interface.h"
using namespace std;
int main()
{
student studentDetails[3]; // Creation of class array object to store 3 objects / Maybe ive declared my array to hold 3 class objects incorrectly?
for (int i = 0; i < 3; i++)
{
studentDetails[i].setstudent(studentName, ID, studentNumber, diploma); // function call to set class variables for the objects
}
return 0;
}
If anyone can please point out what I've done wrong and point me in the right direction would be very appreciated.
Error by CodeBlocks:
||=== Build: Debug in student (compiler: GNU GCC Compiler) ===|
C:\Users\nicbe\Desktop\Student\student\main.cpp||In function 'int main()':|
C:\Users\nicbe\Desktop\Student\student\main.cpp|12|error: 'studentName' was not declared in this scope|
C:\Users\nicbe\Desktop\Student\student\main.cpp|12|error: 'ID' was not declared in this scope|
C:\Users\nicbe\Desktop\Student\student\main.cpp|12|error: 'studentNumber' was not declared in this scope|
C:\Users\nicbe\Desktop\Student\student\main.cpp|12|error: 'diploma' was not declared in this scope|
||=== Build failed: 4 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
The error is exactly what it says: was not declared.
in your main function:
studentDetails[i].setstudent(studentName, ID, studentNumber, diploma);
suddenly these four arguments appear out of thin air(?).
Not sure if you have just excluded that part or what.
I'm facing a problem for the past couple of days.
First of all, I had a project that I've done. But now I've to split it's classes.
Here's how I split the classes (a class as an example):
Header file:
#ifndef QUESTION_H
#define QUESTION_H
#include <string>
#include <iostream>
#include <fstream>
#include "Answer.h"
using namespace std;
// Name -- hold a first and last name
class Question {
protected:
string type; // Type of the question, e.g MC or TF
string text; // Text of the question
public:
// Default constructor
Question ();
// Getters and setters
string getType();
string getText();
void setType (string t);
void setText (string t);
// displayText -- Display the text of the question, unformatted at present
void displayText();
// Template pattern -- algorithm in parent which does its work calling child methods
virtual void displayAnswers();
virtual void display ();
// Virtual pure functions that must be implemented by each derived class
virtual int grade (Answer*); // grade a given answer
virtual Answer* readAnswer(istream &); // read a user's answer
};
#endif
Alright, now here is the implementation:
#include "Question.h"
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
Question::Question () { type = ""; text = ""; }
// Getters and setters
string Question::getType() { return type; }
string Question::getText() { return text; }
void Question::setType (string t) { type = t; }
void Question::setText (string t) { text = t; }
// displayText -- Display the text of the question, unformatted at present
void Question::displayText() {
cout << text;
}
// Template pattern -- algorithm in parent which does its work calling child methods
void Question::displayAnswers(){ }// Require derived classes to implement
void Question::display () {
Question::displayText();
Question::displayAnswers(); // Call derived class's displayAnswers
}
// Virtual pure functions that must be implemented by each derived class
int Question::grade (Answer*){ return 0; } // grade a given answer
Answer* Question::readAnswer(istream &){ return 0; } // read a user's answer
Ok, so I've done the other classes the same exact way.
Now what's left is the MakeFile, here it is:
project: Question MCQuestion TFQuestion Answer IntAnswer CharAnswer Main
g++ -std=c++11 Question MCQuestion TFQuestion Answer IntAnswer CharAnswer Main -o project
.cc.o:
g++ -std=c++11 -c <−o#
Now when I try running make it brings up this message:
g++ Question.cpp -o Question
/usr/lib/gcc/i586-suse-linux/4.7/../../../crt1.o: In function `_start':
/home/abuild/rpmbuild/BUILD/glibc-2.17/csu/../sysdeps/i386/start.S:113: undefined reference to `main'
collect2: error: ld returned 1 exit status
make: *** [Question] Error 1
Can somebody explains it? or what am I doing wrong?
Thanks.
Edited:
Main.cc :
#include <iostream>
#include <fstream>
#include <string>
#include "Question.h"
#include "MCQuestion.h"
#include "TFQuestion.h"
#include "Answer.h"
#include "IntAnswer.h"
#include "CharAnswer.h"
#include <vector>
using namespace std;
int main () {
vector<Question *> questions; // Holds pointers to all the questions
ifstream infile ("questions.txt"); // Open the input file
int totalCorrect = 0; // Initialize the count from number of correct answers
// Read each question and place it into the questions vector
string questionType;
while ( getline (infile, questionType) ) {
if (questionType == "MC") {
MCQuestion *mc = new MCQuestion();
mc->read(infile);
questions.push_back(mc);
}
else if ( questionType[0] == 'T' or questionType[0] == 'F' ) {
TFQuestion* tf = new TFQuestion();
tf->read(infile);
tf->setAnswer(questionType[0]);
questions.push_back(tf);
}
else {
cout << "Input file is corrupt. Expected to find MC, T or F; found \"" << questionType << "\" instead." << endl;
}
}
infile.close();
// Pose each question, read and grade answers, tally total
int questionNo = 0;
for (auto &question: questions) {
// Pose the question
questionNo++; cout << questionNo << ". ";
question->display();
// Get the user's answer
Answer* ans = question->readAnswer(cin);
// Grade it and increment total
int correct = question->grade(ans);
totalCorrect = totalCorrect + correct
// Inform the user as to whether or not they got the question correct
cout << "Your answer was " << (correct?"":"not ") << "correct\n" << endl;
}
// Print the overall score
cout << "Your overall score is " << totalCorrect << "/"
<< questions.size() << endl;
return 0;
}
You create Makefile with lot of mistakes:
Should be something like this:
project: Question.o
g++ -std=c++11 $^ -o $#
.cc.o:
g++ -std=c++11 -c $< -o $#
add other dependencies into project in similar way, not forget defining main function in some of your .cc files.
just a beginner student learning basic C++. I'm trying to figure out the best way to:
Turn a char array Name of 20 into a string that can be printed.
I found in other Stack Overflow topics to use "str()" such as "str(Name)", but it always comes up 'identifier not found'.
cout << "Name:" << str(Name) << endl;
Set a char array of 20 characters. For some reason, the following gives me errors when declaring. I've tweaked it so many times, but I cannot get why it won't give.
TESCStudent.Name[20] = {'S','u','p','e','r','P','r','o','g','r','a','m','m','e','r','\0'};
Full code I have so far:
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
//Step 1
struct StudentRecord
{
char Name[20];
//Accessor
void printInfo() const;
};
void StudentRecord::printInfo() const
{
cout << "Name:" << str(Name) << endl;
}
int main()
{
//Step 2
StudentRecord TESCStudent;
TESCStudent.Name[20] = {'S','u','p','e','r','P','r','o','g','r','a','m','m','e','r','\0'};
//Step 3
TESCStudent.printInfo();
_getch();
return 0;
}
Given that you are at a very beginner level, just use std::string:
#include <iostream>
#include <conio.h>
#include <string>
struct StudentRecord {
std::string Name;
void printInfo() const {
std::cout << "Name:" << Name << '\n';
}
};
int main() {
StudentRecord TESCStudent;
TESCStudent.Name = "SuperProgrammer";
TESCStudent.printInfo();
_getch();
}
Live demo
The syntax like this:
char Name[20] = {'S','u','p','e','r','\0'};
is used to initialize a variable when you define it. However, in your case,
StudentRecord TESCStudent;
TESCStudent.Name[20] = ...;
You've already defined it on the line before, so you can't "initialize", you have to "assign" it.
This is pretty much why you use std:string instead of char[].
I have an assignment for my OOP class to create a rudimentary calculator. The goal of the assignment is to practice namespaces and exception handling.
I will paste the text of the problem for clarity:
You have to implement the class Kalkulator which solves rudimentary mathematical expressions and returns the result as an integer.
The class Kalkulator should be put in a namespace called Matematika. The whole class needs to be implemented in the header file without a .cpp file.
You have to define two exceptions and throw them in the correct situation(they are caught in the main function)
IncorrectDataExc put the class into the namespace Matematika->Exceptions
InvalidOperationExc put the class into the namespace Matematika->Exceptions
and they also gave me the main function:
#include <iostream>
#include <string>
#include "Kalkulator.h"
#include "IncorrectDataExc.h"
#include "InvalidOperationExc.h"
using namespace std;
int main()
{
string s;
getline(cin, s);
try
{
Matematika::Kalkulator kalkulator;
cout << kalkulator.izracunaj(s) << endl;
}
catch(Matematika::Exceptions::IncorrectDataExc)
{
cout << "Exception IncorrectData" << endl;
}
catch(Matematika::Exceptions::InvalidOperationExc)
{
cout << "Exception InvalidOperation" << endl;
}
return 0;
}
The problem I'm having is that i don't know what to throw when i get an exception and i don't know how the InvalidOperationExc and IncorrectDataExc classes should look like because i don't know what the catch functions are actually catching(an object?)
I have to create 3 header files:
IncorrectDataExc.h
InvalidOperationExc.h
Kalkulator.h
This is what i have so far
#pragma once
#include <string>
#include <sstream>
using namespace std;
namespace Matematika{
class Kalkulator{
private:
public:
int izracunaj(string mojString)
{
int prviBroj = 0;
int drugiBroj = 0;
char operacija = ' ';
stringstream ss(mojString);
ss >> prviBroj >> operacija >> drugiBroj;
if(operacija != '*' && operacija != '+' && operacija != '/' && operacija != '-')
{
Matematika::Exceptions::InvalidOperationExc greska1;
throw greska1;
}
if(prviBroj % drugiBroj != 0)
{
Matematika::Exceptions::IncorrectDataExc greska2;
throw greska2;
}
}
};
}
and I'm getting some errors:
'Exceptions': the symbol to the left of a '::' must be a type
'InvalidOperationExc' : is not a member of 'Matematika'
'InvalidOperationExc' : undeclared identifier
missing ';' before identifier 'greska1'
'greska1' : undeclared identifier
'greska1' : undeclared identifier
I don't know what I'm doing wrong. The part that is confusing me the most is this
catch(Matematika::Exceptions::IncorrectDataExc)
what is the catch function receiving?
Pretty self explanatory errors:
'InvalidOperationExc' : is not a member of 'Matematika'
In other words, it doesn't exist. This
Matematika::Exceptions::InvalidOperationExc greska1;
resulted in the error. You should either change the InvalidOperationExc to something else or create it in Matematika.
int izrakunaj() doesn't need Matematika::... to access members of namespace Matematika because it is also a member.
namespace ns
{
int integer; //ns::integer
void set0(){integer=0;} //modifies the variable above
void set1(){ns::integer=1;} //modifies the variable below
namespace ns
{
int integer; //ns::ns::integer
}
}
Header file
#include <iostream>
#include <cstring>
const unsigned MaxLength = 11;
class Phone {
public:
Phone(const char *phone) {
setPhone(phone);
}
void setPhone(const char Phone[ ]);
const char* getPhone();
private:
char phone[MaxLength+1];
};
Cpp file
#include "Phone.h"
#include <iostream>
#include <ctype.h>
#include <cstring>
using namespace std;
bool checkNum(char num[]);
void Phone::setPhone(const char Phone[ ]) {
strncpy(phone, Phone, MaxLength);
phone[MaxLength] = '\0';
}
const char* Phone::getPhone() {
return phone;
}
int main() {
Phone i1("12345678901");
cout << i1.getPhone() << endl;
if (checkNum(i1.getPhone))
cout << "Correct" << endl;
else
cout << "Invalid Wrong" << endl;
}
bool checkNum(char num[]) {
bool flag = true;
if (isdigit(num[0]) == 0)
flag = false;
return flag;
}
When I tried to compile, I get this error:
error C3867: 'Phone::getPhone':
function call missing argument list;
use '&Phone::getPhone' to create a
pointer to member
I'm getting an error on this line "if (checkNum(i1.getPhone))". I created a Phone object and what I am trying to do is use the function checkNum to see if the first index of the array is a number. Am I referencing the object wrong? Should I use indirect selection operator instead? Any idea what I am doing wrong?
Thanks
You are missing a pair of parentheses after getPhone in if (checkNum(i1.getPhone)); it should be if (checkNum(i1.getPhone())).
The line:
if (checkNum(i1.getPhone))
should be
if (checkNum(i1.getPhone()))