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;
}
Related
enter image description hereI am trying out some STL programs. I have declared a vector in main and tried to run the program it is working but if i declare the same(vector) inside the class then am getting a compilation error. I think compiler is not recognizing vector(declared inside the class).
I have tried with std:: also still same error. I am using netbeans IDE and cigwin compiler.
please find the code below
#include <cstdlib>
#include <iostream>
#include <vector>
#include <cctype>
using namespace std;
/*
*
*/
class vectorcl
{
vector<int> v(10);
int i;
public:
vectorcl();
void add_vector();
void dis_vector();
};
vectorcl :: vectorcl()
{
for(i =0;i<10 ;i++)
{
v[i] = 0;
}
}
void vectorcl :: dis_vector()
{
cout<< " The vale is : \n";
for(i =0;i<10 ;i++)
{
cout << "\t " <<v[i];
}
}
void vectorcl :: add_vector()
{
for (i =0 ; i<10; i++)
{
v[i] = i+1;
}
}
int main(int argc, char** argv) {
// vector<int> vp(10);
// for(int j =0;j<10 ;j++)
// {
// cout << " " << vp[j];
// }
vectorcl v1;
v1.dis_vector();
v1.add_vector();
v1.dis_vector();
return 0;
}
Please help me in this, my question is why my compiler is not recognizing vector declared inside a class.
error : expected identifier before numeric constant
expected ',' or '...'before numeric constant
Error
You can not use vector<int> v(10); as member variable. The solution is to replace it by vector<int> v; and add this alter the constructor like this:
vectorcl::vectorcl():
v(std::vector<int>(10,0/* This 0 is instead of the for-loop*/)){
}
Or another option is to declare it as :
std::vector<int> v = std::vector<int>(10);
P.S. there is no need to declare int i as class member. Just declare it in every function you need.
From first glance, you are trying to call the constructor in the class prototype: vector<int> v(10);. Your constructor for that class will be called in your wrapper class constructor unless you use a member initialization list.
Edit: using member initialization
vectorcl :: vectorcl(): v(10)
{
}
Friend function unable to access private member of the class in which it was declared
I am trying to recreate a sample program I am reading in a book demonstrating the use of a friend function. I am getting an error in the ever annoying "Intellisense" with Visual Studio which I frankly can't stand, saying that my defined friend function does not have access to the private member in which the declaration of the friend function exists. The code in different files is as follows:
Main.cpp:
#include "stdafx.h"
#include <iostream>
#include "Budget.h"
using namespace std;
int main() {
return 0;
}
Budget.h
#pragma once
#include "Auxi.h"
class Budget {
public:
Budget() {
divisionBudget = 0;
}
double getDivisionBudget() const {
return divisionBudget;
}
void addBudget(int n) {
divisionBudget += n;
corporateBudget += n;
}
double getCorporateBudget() {
return corporateBudget;
}
static void setCorporateBudget(double n) {
corporateBudget = n;
}
friend void AuxillaryOffice::addBudget(double, Budget &);
private:
static double corporateBudget;
double divisionBudget;
};
double Budget::corporateBudget = 0;
Auxi.h
#pragma once
class Budget;
class AuxillaryOffice {
public:
AuxillaryOffice() {
divisionBudget = 0;
}
void addBudget(double n, Budget &b);
private:
double divisionBudget;
};
Auxi.cpp
#include "stdafx.h"
#include "Auxi.h"
#include "Budget.h"
// class Budget; Do I need this here?
void AuxillaryOffice::addBudget(double n, Budget &b) {
divisionBudget += n;
b.corporateBudget += n; // THIS IS THE ERROR LINE
}
In the immediately above Auxi.cpp file, I am getting an error on the b.corporateBudget += n; line it says that corporateBudget is inaccessible. Is this all legal C++ code or is there something I am missing in this example?
Thanks.
Butget.h
#pragma once
#include "Auxi.h"
class Budget {
public:
Budget() {
divisionBudget = 0;
}
double getDivisionBudget() const {
return divisionBudget;
}
void addBudget(int n) {
divisionBudget += n;
corporateBudget += n;
}
double getCorporateBudget() {
return corporateBudget;
}
static void setCorporateBudget(double n) {
corporateBudget = n;
}
friend void AuxillaryOffice::addBudget(double, Budget &);
private:
static double corporateBudget;
double divisionBudget;
};
double Budget::corporateBudget = 0; // HERE ERROR!!!
You should move double Budget::corporateBudget = 0 to Auxi.cpp.
You are trying to declare a method (AuxillaryOffice::addBudget) as friend of your class (Budget). I believe that it is not possible to declare a single method as friend. I can see two solutions here:
Restructure your program that AuxillaryOffice::addBudget becomes a function (not a class method).
Make class AuxillaryOffice a friend of class Budget.
Please, consider reading this article to get more information about friends.
Intellisense uses another compiler to check your code, so it can sometimes give different results. The error it gives you here is wrong - your code works.
There is just one error that probably prevents your code from compiling. You define the static corporateBudget in the header. This is a problem as it may be defined multiple times if the header is included multiple times (like you did here).
The cleanest solution would be to create a file Budget.cpp and define it there.
This question already has answers here:
Why can templates only be implemented in the header file?
(17 answers)
Closed 9 years ago.
I am trying to code a toy program to exercise C++, but I got a weird undefined reference error that I can not solve.
My code consists of 3 file:
ex13_6.h:
#include<vector>
namespace ex13_6 {
template<class T> class Cmp {
public:
static int eq(T a, T b) {return a == b;}
static int lt(T a, T b) {return a < b;}
};
template<class T, class C = Cmp<T> > void bubble_sort(std::vector<T> &v);
}
ex13_6.cpp
#include<vector>
#include"ex13_6.h"
namespace ex13_6 {
template<class T, class C = Cmp<T> > void bubble_sort(std::vector<T> &v) {
int s = v.size();
T swap;
for (int i=0; i<s; i++) {
for (int j=0; j<s; j++) {
if (C::lt(v.at(j), v.at(i))) {
swap = v.at(i);
v.at(i) = v.at(j);
v.at(j) = swap;
}
}
}
}
}
main.cpp:
#include"ex13_6.h"
#include<iostream>
#include<vector>
using namespace std;
using namespace ex13_6;
int main() {
// Sort using default comparison for int
vector<int> v_int;
for (int i=0; i<10; i++) {
v_int.push_back(10-i);
}
bubble_sort(v_int);
cout << "sort of int vector:\n";
for (vector<int>::const_iterator it = v_int.begin(); it != v_int.end(); it++) {
cout << ' ' << *it;
}
cout << '\n';
}
And I am compiling using:
g++ main.cpp -o main -std=gnu++0x ex13_6.cpp
Here is the error message:
/tmp/ccRwO7Mf.o: In function `main':
main.cpp:(.text+0x5a): undefined reference to `void ex13_6::bubble_sort<int, ex13_6::Cmp<int> >(std::vector<int, std::allocator<int> >&)'
collect2: ld returned 1 exit status
I really appreciate any help!
Move your implementation of the bubble_sort template into your header file.
Templates are not like generics from Java, all the magic happens at compile time in C++. In order for the compiler to generate the code for each template instantiation, it must be visible, and to do that, it must be in the header (or some other file) and included in each translation unit that uses it.
Your templated function definition should be in the ex13_6.h file:
#include<vector>
namespace ex13_6 {
template<class T> class Cmp {
public:
static int eq(T a, T b) {return a == b;}
static int lt(T a, T b) {return a < b;}
};
template<class T, class C = Cmp<T> > void bubble_sort(std::vector<T> &v) {
int s = v.size();
T swap;
for (int i=0; i<s; i++) {
for (int j=0; j<s; j++) {
if (C::lt(v.at(j), v.at(i))) {
swap = v.at(i);
v.at(i) = v.at(j);
v.at(j) = swap;
}
}
}
}
}
You need to put the template implementation in the header file.
When instantiating a template the compiler needs to "see" the implementation, so if you just include the header, the implementation needs to be there.
Don't include a .cpp file.
I have a class SourceComponent, and its derived class, PeriodicSourceComponent.
Implementations are:
class SourceComponent : public Component
{
protected:
friend class UserInterface;
friend void readInput();
public:
virtual int returnType();
virtual int propagateLogic();
virtual void sourcePropagation(float);
virtual void accept(VisitorSources&);
SourceComponent();
};
and
#include "source_component.h"
class PeriodicSourceComponent : public SourceComponent
{
private:
int frequency;
friend void main();
friend void readInput();
friend class UserInterface;
public:
void sourcePropagation(float);
int returnType();
PeriodicSourceComponent();
};
When I try in some different class/method to do:
SourceComponent* s = new PeriodicSourceComponent;
it won't let me, sayin "a value of type periodicblabla cant be assigned to value of type sourceblabla". Why?
Edit:
Ok, in my main it looks lke this:
#include "source_component.h"
#include "periodic_source_component.h"
void main()
{
SourceComponent* s = new PeriodicSourceComponent;
}
And implementations of both classes:
source.cpp:
#include "source_component.h"
SourceComponent::SourceComponent()
{
outputState = -1;
}
int SourceComponent::propagateLogic()
{
return 1;
}
int SourceComponent::returnType()
{
return 5;
}
and periodic.cpp
#include "periodic_source_component.h"
PeriodicSourceComponent::PeriodicSourceComponent()
{
outputState = 0;
}
int PeriodicSourceComponent::returnType()
{
return 3;
}
void PeriodicSourceComponent::sourcePropagation(float time)
{
float t = time, period;
period = 1000000/frequency;
if(t > period)
{
while(t >= period)
t -= period;
}
if(t <= (period/2))
outputState = 0;
else
outputState = 1;
}
and its not working... (outputState is a member of class Component, base class of SourceComponent)
and the error message: A value of type "PeriodicSourceComponent*" cannot be assigned to a value of type "SourceComponent*".
Important Edit
When I try to compile, the actual compiler error is at PeriodicSourceComponent declaration, it says: "Base class undefined".
and also, I have two other derived classes from SourceComponent, but I don't see how they could interfere with this one..
EDIT 4
Ok so I figured out what causes the error, you were right of course, it something else I didn't post. I have class VisitorSources, heres definition:
#ifndef __VISITOR_SOURCES_H__
#define __VISITOR_SOURCES_H__
#include "component.h"
#include "impulse_source_component.h"
#include "arbitrary_source_component.h"
#include "periodic_source_component.h"
class VisitorSources
{
protected:
VisitorSources();
public:
virtual void visitImpulseSource(ImpulseSourceComponent*);
virtual void visitArbitrarySource(ArbitrarySourceComponent*);
virtual void visitPeriodicSource(PeriodicSourceComponent*);
void visitSource(int, float);
};
#endif
And its implementation is not yet written:
#include "visitor_sources.h"
void visitSource(int type, float time)
{
}
void VisitorSources::visitArbitrarySource(ArbitrarySourceComponent* a)
{
}
When I comment out the entire Visitor class and implementation, the above-mentioned errors are gone for some reason. I have no idea why...
The only error that remains is that when I try to use s->frequency, it says that frequency is not a member of SourceComponent, which is true, but it is a member of PeriodicSourceComponent, which is why I used the cast in the first place..
Finally, here's the Component class, the main class for all almost all other classes in the project :P
#ifndef __COMPONENT_H__
#define __COMPONENT_H__
#include <iostream>
#include <vector>
class Component
{
friend class UserInterface;
friend void readAndSimulate();
protected:
Component();
int numOfInputs;
int numOfOutputs;
std::vector<Component*> inputs;
std::vector<Component*> outputs;
friend void main();
float lengthOfSimulation;
int typeIfSource;
public:
int outputState;
virtual int propagateLogic() = 0;
virtual int returnType();
int beginPropagation();
virtual void sourcePropagation(float);
~Component();
};
#endif
And implementation:
#include "component.h"
#include <conio.h>
Component::Component()
{
}
int Component::beginPropagation()
{
std::vector<Component*>::const_iterator iter = outputs.begin();
for(;iter<outputs.end();++iter)
{
if ((*iter)->outputState == -2)
{
(*iter)->outputState = outputState;
return (*iter)->outputState;
}
}
std::vector<Component*>::const_iterator it = outputs.begin();
int finishedCycle, x;
while(1)
{
finishedCycle = 1;
for(; it < outputs.end(); ++it)
{
x = (*it)->propagateLogic();
if(!x)
finishedCycle = 0;
}
if(finishedCycle) break;
it = outputs.begin();
}
it = outputs.begin();
for(;it<outputs.end();++it)
(*it)->beginPropagation();
}
int Component::returnType()
{
return 0;
}
void Component::sourcePropagation(float)
{
}
Component::~Component()
{
std::vector<Component*>::const_iterator it = inputs.begin();
for(; it < inputs.end(); ++it)
{
if((*it) != NULL)
{
delete *it;
Component* p = *it;
p = NULL;
}
}
it = outputs.begin();
for(; it < inputs.end(); ++it)
{
if((*it) != NULL)
{
delete *it;
Component* p = *it;
p = NULL;
}
}
}
Are you using include guards in all your header files?
Not having them can cause the kinds of problems you're seeing.
Three guesses:
You copied and pasted code between header files and forgot to change the #include guards.
You use precompiled headers and included something before the #include "stdafx.h".
If you use precompiled headers, try deleting the .pch file.
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.