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

时间:2012-03-30 12:18:06

标签: c++ class function object parameters

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

坚持使用语法。

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

谢谢!

1 个答案:

答案 0 :(得分:2)

你的主要内容有点不稳定。

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

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