2

How can I port these structures to arduino ide, I also get error when I define pointers

// pointer to classes example
#include <iostream>
using namespace std;

class Rectangle {
  int width, height;
public:
  Rectangle(int x, int y) : width(x), height(y) {}
  int area(void) { return width * height; }
};


int main() {
  Rectangle obj (3, 4);
  Rectangle * foo, * bar, * baz;
  foo = &obj;
  bar = new Rectangle (5, 6);
  baz = new Rectangle[2] { {2,5}, {3,6} };
  cout << "obj's area: " << obj.area() << '\n';
  cout << "*foo's area: " << foo->area() << '\n';
  cout << "*bar's area: " << bar->area() << '\n';
  cout << "baz[0]'s area:" << baz[0].area() << '\n';
  cout << "baz[1]'s area:" << baz[1].area() << '\n';       
  delete bar;
  delete[] baz;
  return 0;
}

In CPP shell it works

I try to put it like this

class Rectangle {
  int width, height;
public:
  Rectangle(int x, int y) : width(x), height(y) {}
  int area(void) { return width * height; }
};

  Rectangle obj (3, 4);
  Rectangle * foo, * bar, * baz;
  foo = &obj;
  bar = new Rectangle (5, 6);
  baz = new Rectangle[2] { {2,5}, {3,6} };

void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

}

I get an error

sketch_nov27a.ino:10:3: error: 'foo' does not name a type
sketch_nov27a.ino:11:3: error: 'bar' does not name a type
sketch_nov27a.ino:12:3: error: 'baz' does not name a type
Error compiling.
1
  • Should I lough or cry? Commented Nov 27, 2014 at 7:25

2 Answers 2

2

The problem is that the lines saying foo = ... etc. are assignment operations. C++ lets you declare and immediately initialise variables at global scope, but after that you can only assign to them inside a function. In your original program, all your declarations/assignments were inside main(), which is why it worked there.

For your Arduino program, you could change the assignments to initialisations instead (in global scope):

Rectangle obj (3, 4);
Rectangle * foo = &obj;
Rectangle * bar = new Rectangle (5, 6);
Rectangle * baz = new Rectangle[2] { {2,5}, {3,6} };

Alternatively, you could leave the declarations in global scope and move the assignments into setup():

Rectangle obj (3, 4);
Rectangle * foo, * bar, * baz;

void setup() {
    foo = &obj;
    bar = new Rectangle (5, 6);
    baz = new Rectangle[2] { {2,5}, {3,6} };
}
0

You put a bunch of code in a place where you can't have it. Move the assignments into a function body.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.