Creating a template class in C++ on Xcode - c++

I'm supposed to create a template class for an assignment, but I'm getting lots of different errors that I don't really understand, can someone please help me? I have attached the cp and header files that I wrote. I know this is probably very simple but I'm new to this, thank you!
#ifndef __Template_example__Initialisedchecker__
#define __Template_example__Initialisedchecker__
#include <stdio.h>
template <class data>
class Initialisedchecker
{
private:
data item;
bool definedOrN;
public:
Initialisedchecker()
{
definedOrN = false;
}
void setItem(const data&)
{
std::cin >> item;
definedOrN = true;
}
void displayItem()
{
if (definedOrN)
{
std::cout << item;
}
else
{
std::cout << "error, your item is undefined";
}
}
};
#endif
And this is the main:
#include <iostream>
#include "Initialisedchecker.h"
using namespace std;
int main()
{
item <int> x;
displayItem();
x = 5;
displayItem();
}
Sorry, I forgot to add the errors I'm getting, the header file doesn't give any errors, but in the main, it says:
Use of undeclared identifier 'display item' ,
Use of undeclared identifier 'item' ,
Use of undeclared identifier 'x' ,
Expected a '(' for function-style cast or type construction

The class template is called Initialisedchecker, not item. And you need to call the member function on the object. You need:
int main()
{
Initialisedchecker <int> x;
x.displayItem();
// this is strange: x = 5;
// maybe use:
// x.setItem( 5 );
x.displayItem();
}

Related

C++: Identifier of class name in same namepace undefined

I have two classes SHCalculator and SphericalLightProbe in separate files. I completely stripped them down to present the error I'm getting so these are the four files:
SHCalculator.h
#pragma once
namespace SphericalHarmonics
{
class SHCalculator
{
private:
public:
void Test();
SphericalLightProbe Test2();
};
}
SHCalculator.cpp
#include "pch.h"
#include "SphericalLightProbe.h"
#include "SHCalculator.h"
namespace SphericalHarmonics
{
void SHCalculator::Test()
{
SphericalLightProbe sp(2, 3.4f);
for (int i = 0; i < sp.coeffs.size(); i++)
{
std::cout << sp.coeffs[i] << std::endl;
}
}
SphericalLightProbe SHCalculator::Test2()
{
SphericalLightProbe sp(2, 4.3f);
for (int i = 0; i < sp.coeffs.size(); i++)
{
std::cout << sp.coeffs[i] << std::endl;
}
return sp;
}
}
SphericalLightProbe.h
#pragma once
namespace SphericalHarmonics
{
class SphericalLightProbe
{
private:
public:
SphericalLightProbe() { }
SphericalLightProbe(int numCoeffs);
SphericalLightProbe(int numCoeffs, float value);
std::vector<Eigen::Vector3f> coeffs;
};
}
SphericalLightProbe.cpp
#include "pch.h"
#include "SphericalLightProbe.h"
namespace SphericalHarmonics
{
SphericalLightProbe::SphericalLightProbe(int numCoeffs)
{
coeffs.resize(numCoeffs);
}
SphericalLightProbe::SphericalLightProbe(int numCoeffs, float value)
{
coeffs.resize(numCoeffs, Eigen::Vector3f(value, value, value));
}
}
This gives me a bunch of errors:
C2238 unexpected token(s) preceding ';'
C2059 syntax error: '('
Message see declaration of 'SphericalHarmonics::SHCalculator'
E0020 identifier "SphericalLightProbe" is undefined
C3646 'Test2': unknown override specifier
C2039 'Test2': is not a member of 'SphericalHarmonics::SHCalculator'
If I remove Test2() by commenting it out, all errors disappear. I'm trying to understand why.
You are missing the includes in your SHCalculator.h header;
Try something like:
#pragma once
#include "SphericalLightProbe.h"
namespace SphericalHarmonics
{
class SHCalculator
{
private:
public:
void Test();
SphericalLightProbe Test2();
};
}
Note that if your SHCalculator.cpp file includes above, the duplicate #include "SphericalLightProbe.h" line is not required.
But if you want to avoid for whatever reason the include, use forward declaration instead, like:
#pragma once
namespace SphericalHarmonics {
class SphericalLightProbe;
// ...
} // namespace SphericalHarmonics
Note that forward declaration normally does not force you to switch to pointers (like SphericalLightProbe *).

Function was not declared in this scope, even though header file is present

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;
}

call a function from an array of vectors

In following code, i get an error on line 33. Why? What is the correct syntax?
Surely I made some stupid mistake ... unfortunately I'm trying to better understand the vectors.
#include <iostream>
#include <vector>
class firstClass
{
public:
firstClass(int x, int y):sum(x+y)
{
}
void getSum()
{
std::cout << sum << std::endl;
}
private:
int sum;
};
class secondClass
{
public:
secondClass(int dim)
{
obj = new std::vector<firstClass>(dim,firstClass{3,5});
}
private:
std::vector<firstClass>*obj;
};
int main()
{
secondClass*obj2;
obj2 = new secondClass(4);
obj2->(*obj)[0].getSum(); //HERE!
return 0;
}
Error:
error: expected unqualified-id before '(' token
error: 'obj' was not declared in this scope
The correct syntax for accessing the data member should be:
(*(obj2->obj))[0].getSum();
Note that secondClass::obj is private data member, so you can't access it in main().
For code sample you showed, you don't need to use raw pointer and new at all.

Can't return a vector of structs declared in header file

I want my getFeatures function to return a vector of structs. The struct I have declared in the header file, but when in my .cpp file I try to write my function name I get a use of undeclared identifier error. The identifier is declared and I can use it in other functions. Also when I write my return statement I get a no viable conversion of vector type to int error. In my header file I have the function prototype and it states my function should return a vector of my struct type, not of type int. What on earth is going on?
#include "Feature_Builder.h"
Feature_Builder::Feature_Builder()
{
int input;
vector<int> intImageVals, temp;
fstream file;
file.open("Integral_Images.txt", ios::in);
if (file.fail())
{
cerr << "File not open!\n";
exit(EXIT_FAILURE);
}
for (int i=0; i<12876; i++)
{
file >> input;
while (input != -1)
{
intImageVals.push_back(input);
file >> input;
}
buildFeatureOne(intImageVals);
buildFeatureTwo(intImageVals);
buildFeatureThree(intImageVals);
buildFeatureFour(intImageVals);
featureIndex = 0;
intImageVals.clear();
}
}
/*****************************************************************************
This is the function with errors! XCode says featureValues is an undeclared
identifier and that features should be of type int!
*****************************************************************************/
vector<featureValues> Feature_Builder::getFeatures()
{
return features;
}
And my header file
#ifndef Facial_Learner_Feature_Builder_h
#define Facial_Learner_Feature_Builder_h
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
class Feature_Builder
{
private:
void buildFeatureOne(vector<int>);
void buildFeatureTwo(vector<int>);
void buildFeatureThree(vector<int>);
void buildFeatureFour(vector<int>);
struct featureValues
{
private:
vector<int> vals;
public:
inline void pushValue(int value)
{vals.push_back(value);}
inline int getValue(int i)
{return vals[i];}
};
int featureIndex;
vector<featureValues> features;
public:
Feature_Builder();
vector<featureValues> getFeatures();
};
#endif
You need the correct scoping for the inner structure:
vector<Feature_Builder::featureValues> Feature_Builder::getFeatures() { ... }

C++ error: explicit qualification in declaration

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