Say i ask a user to input a number, which will be the return value of one of my class members. How do i make it so that it would redirect me another class member, depending on the number input?

Recommended Answers

All 4 Replies

I'm not sure I understand what you want. I'll guess, probably be wrong, and then ask you to describe the problem in a different way. So here's my guess:

#include <iostream>
#include <stdexcept>

class Foo {
  int _a;
  int _b;
  int _c;
public:
  Foo ( int a, int b, int c )
    : _a ( a ), _b ( b ), _c ( c )
  {}

  int get_value ( int i )
  {
    switch ( i ) {
    case 0: return _a;
    case 1: return _b;
    case 2: return _c;
    default:
      throw std::runtime_error ( "Invalid selection" );
    }
  }
};

int main()
{
  Foo f ( 10, 20, 30 );

  for ( int i = -1; i < 4; i++ ) {
    try {
      std::cout<< f.get_value ( i ) <<'\n';
    } catch ( std::runtime_error& ex ) {
      std::cerr<< ex.what() <<'\n';
    }
  }
}

to be exact, this is the problem:

#include <iostream>
using namespace std;

class reck
{
public:
	int menu(); 
	void task();
	void draw();
	void perimeter();
};
//========================================================
int reck::menu()
{
	cout<< "1. draw \n";
	cout<< "2. perimeter \n";
	int k;
	cin>> k;
	return k;
}
//========================================================
void reck::task()
{
	switch(menu())
	{
	case (1) : // what to write that it would redirect to void draw(); ?

Like this?

#include <iostream>

class Foo {
public:
  bool call ( int i )
  {
    switch ( i ) {
    case 0: a(); break;
    case 1: b(); break;
    case 2: c(); break;
    default:
      return false;
    }

    return true;
  }
private:
  void a() { std::cout<<"Calling a\n"; }
  void b() { std::cout<<"Calling b\n"; }
  void c() { std::cout<<"Calling c\n"; }
};

int main()
{
  Foo f;

  for ( int i = -1; i < 4; i++ ) {
    if ( !f.call ( i ) )
      std::cerr<<"Invalid selection\n";
  }
}

here we are. Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.