I have this main function:
#ifndef MAIN_CPP
#define MAIN_CPP
#include "dsets.h"
using namespace std;
int main(){
DisjointSets s;
s.uptree.addelements(4);
for(int i=0; i<s.uptree.size(); i++)
cout <<uptree.at(i) << endl;
return 0;
}
#endif
And the following class:
class DisjointSets
{
public:
void addelements(int x);
int find(int x);
void setunion(int x, int y);
private:
vector<int> uptree;
};
#endif
My implementation is this:
void DisjointSets::addelements(int x){
for(int i=0; i<x; i++)
uptree.push_back(-1);
}
//Given an int this function finds the root associated with that node.
int DisjointSets::find(int x){
//need path compression
if(uptree.at(x) < 0)
return x;
else
return find(uptree.at(x));
}
//This function reorders the uptree in order to represent the union of two
//subtrees
void DisjointSets::setunion(int x, int y){
}
Upon compiling main.cpp (g++ main.cpp)
I'm getting these errors:
dsets.h: In function \u2018int main()\u2019:
dsets.h:25: error: \u2018std::vector > DisjointSets::uptree\u2019 is private
main.cpp:9: error: within this context
main.cpp:9: error: \u2018class std::vector >\u2019 has no member named \u2018addelements\u2019
dsets.h:25: error: \u2018std::vector > DisjointSets::uptree\u2019 is private
main.cpp:10: error: within this context
main.cpp:11: error: \u2018uptree\u2019 was not declared in this scope
I'm not sure exactly whats wrong.
Any help would be appreciated.
You can't access a private element of a class from outside the class. Try making uptree public, or provide a means to access it through DisjointSets. Also, addelements() is a member of class DisjointSets, not vector uptree.
#ifndef MAIN_CPP
#define MAIN_CPP
#include "dsets.h"
using namespace std;
int main(){
DisjointSets s;
s.uptree.addelements(4); // try s.addelements(4)
for(int i=0; i<s.uptree.size(); i++) // try making uptree public
cout <<uptree.at(i) << endl;
return 0;
}
#endif
uptree is a private member of DisjointSets. You could make it public but it's better to create functions in DisjointSets that will provide the functionality you seek without making the members public.
Related
I have been having a lot of issues with header files, and now it seems that the vector that is declared in my header file, Polynomial.hpp, is not being recognized in Polynomial.cpp. I have already included std:: which seems to be a common mistake, so I don't know where to go from here.
Header file:
#ifndef POLYNOMIAL_HPP
#define POLYNOMIAL_HPP
#include<vector>
#include"term.hpp"
class Polynomial {
private:
std::vector<Term> vect;
public:
Polynomial();
~Polynomial();
void add(Term t);
void print();
Polynomial combineLikeTerms();
};
#endif
cpp File:
#include "term.hpp"
#include "Polynomial.hpp"
#include<iostream>
#include<map>
using namespace std;
void add(Term t) {
vect.push_back(t);
}
void print() {
for(int i = 0; i < vect.size(); i++) {
cout << vect[i].toString();
}
}
Polynomial combineLikeTerms() {
Polynomial poly;
map<int, int> combinedPoly;
for(int j = 0; j < vect.size(); j++)
{
combinedPoly.insert(pair<int, int>(vect[j].getExponent(), vect[j].getCoefficient());
}
for(map<int,int>::iterator itr = combinedPoly.begin(); itr != combinedPoly.end(); itr++) {
Term newTerm(itr->second, "x", itr->first);
poly.add(newTerm);
}
return poly;
}
Error (1/6):
Polynomial.cpp:9:5: error: use of undeclared identifier 'vect'
vect.push_back(t);
In Polynomial.cpp you are defining new functions instead of member functions. Change the definitions to use the class name like
void Polynomial::add(Term t) {
vect.push_back(t);
}
Your void add(Term T) in Polynomial.cpp is not the member function of the Polynomial.
You must implement this function as member of Polynomial like this
void Polynomial::add(Term T){
...
}
I think this is a syntax error. First, you defined the add method in the Polynomial class of the header file, but the CPP file did not add the class scope, which caused this problem. So you should adjust your code like this:
void Polynomial::add(Term t) {
vect.push_back(t);
}
The root cause of this problem is that the methods of the class only work within the scope of the class, and if there is a function with the same name inside the class, it will lead to a naming conflict. Therefore, the root cause of this problem is not the reference error of the vector file.
The issue is that instead of defining the members add and print of the class Polynomial, you are defining functions in global scope completely unrelated to the class Polynomial
Make changes in the function definition of void add(Term) and void print() to void Polynomial::add(Term) and void Polynomial::print().
#include "term.hpp"
#include "Polynomial.hpp"
#include<iostream>
#include<map>
using namespace std;
void Polynomial::add(Term t) { // change here
vect.push_back(t);
}
void Polynomial::print() { //change here
for(int i = 0; i < vect.size(); i++) {
cout << vect[i].toString();
}
}
Polynomial combineLikeTerms() {
Polynomial poly;
map<int, int> combinedPoly;
for(int j = 0; j < vect.size(); j++)
{
combinedPoly.insert(pair<int, int>(vect[j].getExponent(), vect[j].getCoefficient());
}
for(map<int,int>::iterator itr = combinedPoly.begin(); itr != combinedPoly.end(); itr++) {
Term newTerm(itr->second, "x", itr->first);
poly.add(newTerm);
}
return poly;
}
I'm trying to run some test code to learn c++, but I am getting an error telling me the reverseDigits function was not declared in the main.cpp scope:
error: 'reverseDigits' was not declared in this scope.
But the #include "Solutions.h" header was included in main.cpp, so I thought that it would be in scope.
I have checkout other questions, but the answers all relate to problems with circular header file inclusion, which I don't think is the problem here.
Do you know why I am seeing that error?
Solution.h
#ifndef SOLUTION_H
#define SOLUTION_H
class Solution {
public:
Solution();
~Solution();
int reverseDigits(int x);
};
#endif // SOLUTION_H
Solution.cpp
#include "Solution.h"
#include <string>
Solution::Solution()
{
}
Solution::~Solution()
{
}
int Solution::reverseDigits(int x) {
std::string num_string = std::to_string(x);
std::string reversed_num_string {};
for (int i = num_string.length() - 1; i > 0; i--) {
reversed_num_string.push_back(num_string[i]);
}
return stoi(reversed_num_string);
}
main.cpp
#include <iostream>
#include "Solution.h"
int main()
{
int x {123};
int result = reverseDigits(x);
std::cout << result << std::endl;
return 0;
}
You declared reverseDigits as a member function of the Solution class, then defined it without qualifying it as a member of Solution (Edit: You've since changed it to match declaration and definition, but at point of use, you're trying to use an unqualified function, not a member of a Solution object). The declaration in the .h file is visible, but the definition in the .cpp is unrelated, and not visible to main.cpp.
Declare the function outside the class (since it's clearly unrelated to the class), and it should work, changing to:
class Solution {
public:
Solution();
~Solution();
};
int reverseDigits(int x); // NOT inside the class definition
I'll note: I have no idea why you have a Solution class at all. Defining reverseDigits doesn't require it, so I'm not seeing the point. If this is part of some automated evaluation framework, you'll have to give more details
Along with ShadowRanger's valid suggestion, I'll highlight upon how you could have used the data as part of your Solution class and applied the function on it.
Refactoring your class to
class Solution {
public:
Solution(int data);
~Solution();
int reverseDigits();
private:
int m_data;
};
Solution::Solution(int data)
{
m_data = data;
}
Solution::~Solution()
{
}
Even though you could have used std::reverse, fixing the error on the i>=0 is needed to have your own reverse function
int Solution::reverseDigits() {
std::string num_string = std::to_string(m_data);
std::string reversed_num_string {};
for (int i = num_string.length() - 1; i >= 0; i--) {
reversed_num_string.push_back(num_string[i]);
}
return stoi(reversed_num_string);
}
Now call it from your main() as
int main() {
int x = 123;
Solution sol(x);
std::cout << sol.reverseDigits() << std::endl;
return 0;
}
I am getting the error "error: Invalid use of AppleFarmer::AppleFarmer. I do not know why I am getting this error since I am not trying to pass any input into my Constructor. Is it possible I have an issue with my .h file? What am i doing wrong to get this error?
I have three different files, and I may also be having an issue with linking the code together as I am doing #include for a .cpp file. I am not sure if my code works aside from this error, but I am stuck on this error.
appleFarmerMain.cpp
#include<iostream>
#include "appleFarmer.cpp"
int main(){
AppleFarmer m;
int harvest;
int demand;
m.AppleFarmer();
while(m.endOfMonth()==false){
cout<<"Enter a harvest amount:"<<endl;
cin>>harvest;
m.harvestApples(harvest);
cout<<"Enter a demand:"<<endl;
cin>>demand;
m.sellApples(demand);
cout<<"Apple Inventory: "<<m.getInventory()<<endl;
m.updateCurrentDay();
}
return 0;
}
appleFarmer.cpp
#include "appleFarmer.h"
#include "<iostream>
using namespace std;
AppleFarmer::AppleFarmer(){
for(int i=0;i<30;i++){
sales[i]=0;
harvest[i]=0;
}
}
bool AppleFarmer::sellApples(int demand){
if(demand<= inventory){
sales[currentDay]=demand;
inventory=inventory-demand;
}
else{
sales[currentDay]=0;
}
}
void AppleFarmer::harvestApples(int dayHarvest){
harvest[currentDay]= dayHarvest;
inventory=inventory+dayHarvest;
}
bool AppleFarmer::endOfMonth(){
if (currentDay=maxDays){
return true;
}
else{
return false;
}
}
int AppleFarmer::updateCurrentDay(){
currentDay=currentDay+1;
}
int AppleFarmer::getInventory(){
return inventory;
}
double AppleFarmer::calculateAverageHarvest(){
}
double calculateAverageSales(){
}
void AppleFarmer::printSales(){
}
void AppleFarmer::printHarvest(){
}
appleFarmer.h
#ifndef APPLEFARMER_H
#define APPLEFARMER_H
class AppleFarmer
{
public:
AppleFarmer();
bool sellApples(int);
void harvestApples(int);
bool endOfMonth();
int updateCurrentDay();
int getInventory();
double calculateAverageHarvest();
double calculateAverageSales();
void printSales();
void printHarvest();
private:
int sales[30];
int harvest[30];
int maxDays = 30;
int currentDay = 0;
int inventory = 0;
};
#endif
In C++ you don't call the constructor on an object. That happens at object creation time. The line
m.AppleFarmer();
isn't needed. The constructor is implicitly called here:
AppleFarmer m;
You need to include appleFarmer.h instead of appleFarmer.cpp because the header file (with .h extension) contains the declaration while the .cpp file contains the implementation.
Then you need also to delete m.AppleFarmer(); because the constructor is called during the declaration (AppleFarmer m text line).
I have a simple class which I cannot instantiate and I don't know why...
Please help me !
-------Test.cpp-------
#include<iostream>
using namespace std;
#include "meteo.h"
int main()
{
Meteo meteo;
}
-------meteo.h---------
#ifndef METEO_H
#define METEO_H
class Meteo
{
public:
Meteo();
int Get(int i);
private:
char *list[];
};
#endif
-------meteo.cpp--------
#include "meteo.h"
Meteo::Meteo()
{
list[]("Sec","Venteux","Humide");
}
int Meteo::Get(int i)
{
return list[i];
}
I get the error: "undefined reference to `Meteo::Meteo()'"
It seems that the problem is that the compiler issued an error when was compiling the constructor
Meteo::Meteo()
{
list[]("Sec","Venteux","Humide");
}
and did not generate the object module.
This record
list[]("Sec","Venteux","Humide");
is invalid.
Try to change the class definition like
class Meteo
{
public:
Meteo();
int Get(int i);
private:
const char *list[3];
};
and define the constructor like
Meteo::Meteo() : list { "Sec","Venteux","Humide" }
{
}
The other reason might be that you did not include object module meteo in the project.
Take into account that this member function
int Meteo::Get(int i)
{
return list[i];
}
is also wrong. The type of elements of the array is const char * not int.
I am trying to work on a tutorial that I wasn't able to finish during class and I'm having a hard time figuring out my errors. I have never seen an explicit qualification error before so I'm not even sure where to start. The only resources I can find online for this kind of error has to do when using namespaces and I don't think I am, at least not explicitly (other than namespace std).
I am sure I'm making a stupid mistake somewhere but these are the errors I'm getting:
View.cpp:12:55: error: explicit qualification in declaration of ‘void promptForAnimals(Animal**, int&)’
View.cpp:53:25: error: explicit qualification in declaration of ‘void printDance(Animal*)’
and this is my promptForAnimals function:
void::promptForAnimals(Animal* barn[], int& numAnimals)
{
//Animal* barn[MAX_ANIMALS];
int num;
string name;
cout << "How many birds? ";
cin >> num; cin.ignore();
for (int i=0; i<num; i++) {
cout << "Name " << i+1 << ": ";
getline(cin, name);
barn[numAnimals++] = new Bird(name);
}
etc
}
}
and my printDanceAnimal is empty, just has:
void::printDance(Animal*)
{
}
The errors could very well have to do with my header file, so here it is for good measure:
#ifndef VIEW_H
#define VIEW_H
#include "Animal.h"
#include "defs.h"
#include <iostream>
using namespace std;
class View
{
public:
View();
~View();
void promptForAnimals(Animal**, int&);
void printDance(Animal*);
};
#endif
You miss class name in these function definitions:
Update:
void::promptForAnimals(Animal* barn[], int& numAnimals)
void::printDance(Animal*)
To:
void View::promptForAnimals(Animal* barn[], int& numAnimals)
void View::printDance(Animal*)
void::promptForAnimals(Animal* barn[], int& numAnimals)
This is wrong. Should be:
void View::promptForAnimals(Animal* barn[], int& numAnimals)
{
// ...
}
This error appears when you explicitly specify already opened namespace.
namespace SomeName {
int SomeName::someFunc() { return 0; } //error
}
I suspect, the empty namespace is the name of the global namespace which is always open, so that is why this kind of error occurs in your case, which is equivalent to that:
int ::someFunc() { return 0; } //error again