繁体   English   中英

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

[英]C++ class/object function usage query

我有一个定义函数的类需要作为参数传递。 我想设置这个类的新实例(带参数)作为对象(?)。

陷入语法困境。

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 }

我想为classfunction1定义params,它将在类函数2中使用并分配一个该类型的对象(?),以便intellisense将它拾取。

伪:

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

谢谢!

你的主要是有点不知所措。

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

您定义的类没有任何成员变量,因此它不store任何数据。 它只有两个功能。 所以这意味着您可以使用编译器为每个类定义的“默认构造函数”(如果您愿意,可以提供自己的构造函数)。

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

如果你想提供一个构造函数,你应该做类似的事情:

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;
};

你的主要看起来像:

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.
}

有几点需要注意:您尝试调用第一个构造函数的方式是错误的,您需要变量名后面的参数。 请参阅下面的评论以了解另一件需要注意的事项。

暂无
暂无

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

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