I have two questions relating to classes. I have run into a problem in using classes in multi-file programs. Here are three example files which illustrate the problem I am having and the errors I am getting.
file1.cpp
//file1.cpp
#include<iostream>
#include"file3.h"
using std::cout;
using std::cin;
namespace baz
{
extern MyClass foobar;
}
int main()
{
baz::foobar.setFOO();
baz::foobar.bar();
cout << *baz::foobar.FOO << "\n";
cin.ignore();
return 0;
}
/*errors:
In function `main':
[Linker error] undefined refference to `baz::foobar'
[Linker error] undefined refference to `MyClass::setFOO()'
[Linker error] undefined refference to `baz::foobar'
[Linker error] undefined refference to `MyClass::bar()'
[Linker error] undefined refference to `baz::foobar'
Id returned 1 exit status
*/
file2.c
//file2.c
#include"file3.h"
namespace baz
{
MyClass foobar;
}
void baz::foobar.bar(void)
{
foo = 42;
}
void baz::foobar.setFOO(void)
{
FOO = &foo;
}
file3.h
//file3.h
class MyClass
{
private:
int foo;
public:
void bar(void);
void setFOO(void);
int * FOO;
};
What I was wanting this program to do was display 42 and wait for [Enter] to be pressed; however, it will not compile. As far as I can tell the main program needs to see a function prototype, but if I place
void baz::foobar.bar(void);
void baz::foobar.setFOO(void);
in file3.h then file3.h gets an error! How should I make a prototype?
My other question is how I would be able to get rid of the setFOO() function and say something like
const int & FOO = foo;
inside the class definition. My compiler says this is not allowed. I want FOO to be visible globaly and to reflect the contents of foo but be unmodifiable.
Thanks in advance. :)