Pages: [1]   Go Down
Author Topic: My class does not name a type  (Read 850 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Jr. Member
**
Karma: 1
Posts: 75
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hello guys, I am having surprising amounts of trouble with something that ought to be trivial. The code below compiles fine:

Quote
class Foo {
  public:
    int x;
    
  Foo(float f) {
    x=(int)f;
  }
  
  int getX() {
    return x;
  }
  
};


void setup() {
  
  Foo f = Foo(3.1415927);
  
}

void loop() {
}


My class Foo is perfectly useable in setup and all is perfect with the universe. That is, until I try using it as a return value or an argument to a function e.g. adding this after loop():


Quote
Foo zonk(float f) {
  return Foo(f);
}


Gets me a:
error: 'Foo' does not name a type


while this:

Quote
int zonk(Foo f) {
  return f.getX();
}


tells me that:
error: 'Foo' was not declared in this scope

Why is the great big chunk of code defining the class at the start of the sketch not good enough when trying to use the class in this context?
Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 551
Posts: 46266
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Putting the class definition in a separate file, Foo.h, and #including Foo.h in the sketch lets the int zonk function compile.
Logged

0
Offline Offline
Jr. Member
**
Karma: 1
Posts: 75
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Ah, thank you. I was hoping I wouldn't have to write a library if all I want to do is use a small class but anyway, I did and it worked.
Logged

0
Offline Offline
God Member
*****
Karma: 0
Posts: 511
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

you can also put the class/function prototypes at the beginning of the script.  Which may be more appropriate than splitting things into separate files for this sized application, easier to share it and for folks to run it then too.
Logged

Pages: [1]   Go Up
Jump to: