开发者

C++ class definition

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

void Rectangle::set_values (int a, int b) {
  x = a;
  y = b;
}

I have this class inside of function of anot开发者_StackOverflow中文版her class its giving error: a function-definition is not allowed here before ‘{’ token could you say me why?


You can't have a write a function definition inside another function in C++. If anything, you'll need to write the implementation inside your class declaration, like you did with the area function.


You should separe your declaration (.h) from your implementation (.cpp). If you want to implement some function in your declaration file (nomally for simple functions) you should use the inline reserved word:

Rectangle.h
class Rectangle { 
    int x, y; 
  public: 
    void set_values (int,int); 
    inline int area (void) {return (x*y);} 
}; 

Rectangle.cpp
#include Rectangle.h

void Rectangle::set_values (int a, int b) { 
  x = a; 
  y = b; 
} 


You can make a type in function scope, but you can't declare the function there. You can do this:

class Rectangle { 
   int x, y; 
    public: 
      void set_values (int a, int b) { x = a; y = b; }
      int area (void) { return (x*y); } 
};

But, why not just declare Rectangle normally? It seems useful enough to want to use in other functions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜