I'm being tasked with defining a struct within my main() function, but using it in other files. I have the code working if I define my struct inside my header file, but I cannot figure out how to define struct inside main() and still use it outside its given scope.
Example of what I have now:
3 files: main.cpp, header.h, and function.cpp
main.cpp
#include <iostream>
#include "header.h"
using namespace std;
int main()
{
vector<myStruct> myVec;
myFunction(myVec);
return 0;
}
header.h
#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
#include <vector>
using namespace std;
struct myStruct{
int typeInt;
string typeString;
double typeDouble;
};
void myFunction(vector<myStruct>&);
#endif // HEADER_H_INCLUDED
function.cpp
#include <iostream>
#include <vector>
#include "header.h"
using namespace std;
void myFunction(vector<myStruct>& myVec){
myVec.push_back(myStruct());
myVec[0].typeInt=5;
cout<<myVec[0].typeInt<<endl;
}
Right now, this works for what I need it to do. Unfortunately, I'm told I cannot define struct myStruct inside header.h but instead must have it within main() in main.cpp.
I've tried changing my code to the following (function.cpp unchanged):
main.cpp v2
#include <iostream>
#include "header.h"
using namespace std;
int main()
{
struct myStruct{
int typeInt;
string typeString;
double typeDouble;
};
vector<myStruct> myVec;
myFunction(myVec);
return 0;
}
header.h v2
#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
#include <vector>
using namespace std;
template <typename myStruct>
void myFunction(vector<myStruct>&);
#endif // HEADER_H_INCLUDED
Now I receive the error:
error: 'myStruct' was not declared in this scope on line 7 of function.cpp.
How can I use myStruct in function.cpp, while still defining myStruct in main() of main.cpp?
this way using template is correct, that problem occur in function.cpp right?
you try to define the function "myFunction(..)" in header.h,
and remove function.cpp, this program will work well.
if you must implement that fuction in function.cpp, you have to create a template class.
Related
My code is similar to this one, but the problem is exactly the same: I'm getting an "undefined reference to `Test1::v" in Test1.cpp and in Test2.cpp when compilling the program in VSCode. What am I doing wrong? I'm a bit new on c++ so I just downloaded an extension that made me a project in c++ automatically. When I run the program using Ctrl + Shift + B it gives me this error, but when I do it with the Code Runner extension it doesn't detect the .cpp files.
// Test1.h
#include <iostream>
#include <vector>
using namespace std;
#ifndef TEST1_H
#define TEST1_H
class Test1{
public:
Test1();
static vector<Test1> v;
int a;
};
#endif
//Test1.cpp
#include "Test1.h"
Test1::Test1(){
a = 2;
v.push_back(*this);
}
//Test2.h
#include <iostream>
#include <vector>
using namespace std;
#ifndef TEST2_H
#define TEST2_H
class Test2{
public:
Test2();
double var;
};
#endif
//Test2.cpp
#include "Test2.h"
#include "Test1.h"
Test2::Test2(){
var = 5;
Test1::v[0].a += var;
}
//main.cpp
#include <iostream>
#include "Test1.h"
#include "Test2.h"
using namespace std;
int main(int argc, char *argv[])
{
cout << "Hello world!" << endl;
}
You have declared the static vector in the header file, but you need to define it in a cpp file. Add:
vector<Test1> Test1::v;
to your test1.cpp file. You can learn more about definition vs declaration here.
Also make sure you read this: Why is "using namespace std;" considered bad practice?
You could prepend the class name to call the variable directly since it's static. So, you could do something like:
Test1::Test1(){
// v.push__back(*this); // previous
Test1::v.push_back(*this); // now
}
in Test1.cpp. You'll then get a reference tooltip on your VS Code:
static std::vector<Test1> Test1::v
Which proves it's done.
I'm getting an error everytime I compile the function.cpp file saying that stocks and newStock are not declared in this scope. I'm trying to use a struct inside a vector. Thanks for the help.
This is the main.cpp file
#include <fstream>
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <sstream>
#include <vector>
using namespace std;
struct Stocks
{
int one;
int two;
int three;
};
vector<Stocks> portfolio;
#include "testProject2.h"
int main()
{
buyStock(portfolio);
}
This is the header file.
#include <iostream>
void buyStock(vector<Stocks>& Portfolios);
This is the function.cpp file
#include <iostream>
#include <vector>
#include "testProject2.h"
void buyStock(vector<Stocks>& Portfolios)
{
Stocks newStock;
newStock{1,2,3};
Portfolios.push_back(newStock);
}
Your function.cpp file has no way to know what the Stocks struct is. Define it in the header file:
struct Stocks {
int one;
int two;
int three;
};
And remove its definition from main.cpp.
Also in your header file, you need
#include <vector>
and refer to vector parameter as std::vector<Stocks> &Portfolios (better than using namespace std;)
Your initialization syntax newstock{1,2,3} looks incorrect too.
You use vector in your header file without it being defined.
Try changing the header file to this:
#include <vector>
#include <Stocks.h> // name of .h file where Stocks is defined
void buyStock(std::vector<Stocks>& Portfolios);
// OR
using namespace std::vector;
void buyStock(vector<Stocks>& Portfolios);
I am unsure about the use of separate files for classes. How do I make functions inside the classes? Where do I put it?
QuizMain.cpp:
#include "QuizMain.h"
#include <iostream>
#include <string>
using namespace std;
QuizMain::QuizMain()
{
// Hia stackoverflow
}
QuizMain.h file:
#ifndef QUIZMAIN_H
#define QUIZMAIN_H
#include <string>
using namespace std;
class QuizMain
{
public:
QuizMain();
private:
};
#endif // QUIZMAIN_H
Main file:
#include <iostream>
#include <string>
#include "QuizMain.h"
using namespace std;
int main()
{
QuizMain qm;
return 0;
}
How would I make a class and call it correctly?
This is an example:
QuizMain.cpp file:
#include "QuizMain.h"
#include <iostream>
#include <string>
using namespace std;
QuizMain::QuizMain()
{
// Hia stackoverflow
}
void QuizMain::my_new_function(std::string my_name){
std::cout << "Hi " + my_name +"!" << std::endl;
}
QuizMain.h file:
#ifndef QUIZMAIN_H
#define QUIZMAIN_H
#include <string>
class QuizMain
{
public:
QuizMain();
void my_new_function(std::string my_name);
private:
};
#endif // QUIZMAIN_H
Main file:
#include <iostream>
#include <string>
#include "QuizMain.h"
using namespace std;
int main()
{
QuizMain qm;
qm.my_new_function("foo");
return 0;
}
Anyway, there is no point from asking such a question here. You should probably find a good book/resource and learn how to write and use functions.
Normally you have a header file and cpp file. The header file is where you declare your functions and member variables. The cpp file is where you implement your functions.
quizmain.h
// QuizMain.h file
#ifndef QUIZMAIN_H
#define QUIZMAIN_H
#include <string>
class QuizMain
{
public:
QuizMain(int quizScore);
// declare public functions here
private:
int quizScore; // declare private member variables here.
};
#endif // QUIZMAIN_H
cpp file
// QuizMain.cpp file
#include "QuizMain.h"
#include <iostream>
#include <string>
using namespace std;
QuizMain::QuizMain(int quizScore)
{
this.quizScore = quizScore; // init a quiz score
}
main
Call and create a class object like this
QuizMain quiz(95);
It is easy to do.
If you use the IDE project, the IDE set you to use the any file. Like code::block IDE But if you do not use the IDE project it is a little different to use.
You should write the .h file and then,after all writing you should put .cpp file.
Also you can use interface class that works by poiter.
/// .h file and declaration
#ifndef ONE.H
#define ONE.H
class one {
public:
one();
~one();
};
#include "one.cpp"
#endif ONE.H
then:
/// .cpp file and implementation
one::one(){
std::cout<<"constructor one"<<std::endl;
}
one::~one(){
std::cout<<"destructor one"<<std::endl;
}
then :
#include <iostream>
#include "one.h"
int main()
{
one o;
}
output:
constructor one
destructor one
Process returned 0 (0x0) execution time : 0.010 s
Press ENTER to continue.
I have a header file, RandFunctions.hpp which contains a template function,
#ifndef _RANDFUNCTIONS_HPP_
#define _RANDFUNCTIONS_HPP_
#include <stdlib.h>
#include <time.h>
namespace surena
{
namespace common
{
template<typename RealT> inline
RealT
RealRandom()
{
return rand()/(RealT(RAND_MAX)+1);
}
};
};
#endif
and another header file, Search.hpp which includes RandFunctions.hpp,
#ifndef _SEARCH_HPP_
#define _SEARCH_HPP_
#include "RandFunctions.hpp"
#include <stdlib.h>
#include <time.h>
namespace surena
{
namespace search
{
template<typename RealT>
class CTest
{
public:
CTest() {srand((unsigned)(time(0)));}
RealT
GenRand(){ return common::RealRandom(); }
};
};
};
#endif
when I include Search.hpp in a cpp file, for example,
#include "Search.hpp"
int
main(int argc, char** argv)
{
CTest<float> test;
return(0);
}
I get the following compile time error:
‘RealRandom’ is not a member of ‘surena::common’
What is wrong here?
Since RealRandom is a template function with no parameters, you need to provide a template argument:
GenRand(){ return common::RealRandom<RealT>(); }
^^^^^^^
Also in your main you'd have to qualify your test variable with the proper namespaces:
surena::search::CTest<float> test;
^^^^^^^^^^^^^^^^
I'm a pretty seasoned programmer but I'm just now diving into C++ and it's... well... more difficult than PHP and Python. I keep having unresolved external errors when trying to create an object from some classes. It's broken up into multiple headers and files but here is a basic idea from one of my classes:
die.h:
#ifndef DIE_H
#define DIE_H
using namespace std;
class Die {
public:
int throwDie();
Die();
};
#endif
die.cpp
#include <iostream>
#include <cstdlib>
#include "Die.h"
using namespace std;
int Die::throwDie()
{
return 0;
}
sixsidedie.h
#ifndef SIXSIDEDIE_H
#define SIXSIDEDIE_H
#include "Die.h"
using namespace std;
class SixSideDie : public Die
{
public:
SixSideDie();
int throwDie();
private:
int randNumber;
};
#endif
sixsidedie.cpp
#include <iostream>
#include <cstdlib>
#include <time.h>
#include "Die.h"
#include "SixSideDie.h"
using namespace std;
const int SIX_SIDE = 6;
int SixSideDie::throwDie()
{
srand((unsigned int)time(0));
SixSideDie::randNumber = rand() % SIX_SIDE + 1;
return SixSideDie::randNumber;
}
main.cpp
#include <iostream>
#include <cstdlib>
#include "Die.h"
#include "SixSideDie.h"
#include "TenSideDie.h"
#include "TwentySideDie.h"
using namespace std;
int main()
{
Die* myDice[3];
myDice[0] = new SixSideDie();
myDice[1] = new TenSideDie();
myDice[2] = new TwentySideDie();
myDice[0]->throwDie();
myDice[1]->throwDie();
myDice[2]->throwDie();
system("pause");
return 0;
}
It keeps telling me that each object I create directly above is an unresolved external symbol and I just don't know why. Any thoughts!?
You declared a constructor for Die but never defined it.
Also, you almost certainly want throwDie to be virtual if you intend to override its behavior in derived classes, and you should never use using namespace std; in a header file (and many people, including me, would argue that you shouldn't use it at file-scope at all).
You didn't define your constructor in your cpp files.
Its good practice to define the constructors of the classes. Check this out:
#ifndef DIE_H
#define DIE_H
using namespace std;
class Die {
public:
int throwDie();
Die() { }; // can you spot the difference here?
};
#endif