简体   繁体   English

C ++类/对象函数用法查询

[英]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. 我想为classfunction1定义params,它将在类函数2中使用并分配一个该类型的对象(?),以便intellisense将它拾取。

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. 您定义的类没有任何成员变量,因此它不store任何数据。 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. 请参阅下面的评论以了解另一件需要注意的事项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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