gpt4 book ai didi

C++类/目标函数使用查询

转载 作者:行者123 更新时间:2023-11-28 03:38:59 24 4
gpt4 key购买 nike

我有一个类,其中包含需要作为参数传递的已定义函数。我想将此类(带参数)的新实例设置为对象(?)。

被语法困住。

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 定义参数,它将在 classfunction 2 中使用,并分配一个该类型的对象(?),以便 intellisense 能够识别它。

伪:

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

谢谢!

最佳答案

您的 main 目前有点不稳定。

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

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

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

你的 main 看起来像:

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

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

关于C++类/目标函数使用查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9942770/

24 4 0
文章推荐: twitter-bootstrap - 使用字体大小更改