简体   繁体   中英

C++ class/object function usage query

I have a class with defined functions that need to be passed as parameters. I want to setup a new instance of this class (with parameters) as an object(?).

Getting stuck with the syntax.

class classname{
void classfunction1(int, int);
void classfunction2(int, int);
};

void classname::classfunction1 (int a, int b)
{ // function }

void classname::classfunction2 (int a, int b)
{ // function uses classfunction1 }

I want to define the params for classfunction1, which will be used in classfunction 2 and assign an object(?), of that type so that intellisense will pick it up.

Pseudo:

int main(){
classname(20, 20) object;
object.classfunction2(50, 50);
}

Thanks!

Your main is a bit wonky at the minute.

int main(){
    classname(20, 20) object; // You are incorrectly calling a constructor which does not exist
    object.classfunction2(50, 50); // more like correct behavior.
}

The class you have defined does not have any member variables, so it does not store any data. It only holds two functions. So this means that you can use the "default constructor" that the compiler defines for every class ( you can provide your own if you wish ).

int main(){
    classname object; // Call the default constructor
    object.classfunction1(10, 20); // Call the functions you want.
    object.classfunction2(50, 50); 
}

If you wanted to provide a constructor you should do something like:

class classname{
  public:
    classname(int variable1, int variable2): 
            member1(variable1), member2(variable2){}; //note that there is no return type
    void classfunction1(); //because instead of taking parameters it uses member1 & 2
    void classfunction2(int, int);

  private: 
    int member1;
    int member2;
};

You main would then look like:

int main(){
    classname object(10, 20); // Call the default constructor. Note that the (10, 20) is AFTER "object".
    object.classfunction1();  // Call the function... it will use 10 and 20.
    object.classfunction2(50, 50); //This function will use 50, 50 and then call classfunction1 which will use 10 and 20.
}

A couple of things to note: The way you attempted to call the first constructor was wrong, you need the parameters after the variable name. See comments below for another thing to watch out for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM