在main()中,通过对象名、指向对象的指针、对象的引用三种方式来访问输出函数。
时间: 2024-02-20 10:56:25 浏览: 13
好的,很高兴回答你的问题。在main()函数中,我们可以通过对象名、指向对象的指针、对象的引用三种方式来访问输出函数。假设我们有一个类名为MyClass,它有一个成员函数print()用于输出一些信息。那么,我们可以通过以下三种方式来访问print()函数:
1. 使用对象名访问print()函数:
```
MyClass object;
object.print();
```
2. 使用指向对象的指针访问print()函数:
```
MyClass *ptr = new MyClass;
ptr->print();
delete ptr;
```
3. 使用对象的引用访问print()函数:
```
MyClass &ref = object;
ref.print();
```
以上三种方式都会调用MyClass类的print()函数,并输出相应的信息。希望这个回答能够帮到你。
相关问题
在C++对象中使用函数指针
可以用来实现回调函数或者动态函数调用。在C语言中,函数名是一个指向函数代码起始地址的指针,可以将这个指针作为函数参数,传递给其他函数,让其在适当的时候调用该函数。这个指向函数的指针就是函数指针。它可以通过类型定义来声明,例如:
```
typedef int (*pFunc)(int, int);
```
这个类型定义表示 pFunc 是一个指向以两个 int 类型参数并返回 int 类型值的函数指针。示例代码如下:
```
int add(int a, int b) {
return a+b;
}
int sub(int a, int b) {
return a-b;
}
void doCalculation(int a, int b, pFunc func) {
int result = (*func)(a, b);
printf("The result is: %d\n", result);
}
int main() {
pFunc pAdd = add;
pFunc pSub = sub;
doCalculation(2, 3, pAdd);
doCalculation(10, 5, pSub);
return 0;
}
```
在这个示例中,我们定义了两个函数 add 和 sub,并且声明了一个类型为 pFunc 的函数指针。我们通过将 add 和 sub 函数的指针传递给 doCalculation 函数来实现函数指针的调用。在 doCalculation 函数中,我们使用了 (*func) 来调用传入的函数指针。
定义指向Person::display() 函数的指针,并在main()中通过函数指针的方式调用此函数,
可以这样定义指向Person::display()函数的指针:
```
void (Person::*displayPtr)() = &Person::display;
```
这里使用了类成员函数指针的语法格式,其中`void`表示函数返回值类型,`Person::*`表示指向Person类的成员函数,`displayPtr`为指针名称。
然后在main()中,可以通过函数指针的方式调用此函数,示例代码如下:
```
int main()
{
Person p("Tom", 18);
void (Person::*displayPtr)() = &Person::display;
(p.*displayPtr)(); // 通过函数指针调用Person::display()函数
return 0;
}
```
这里先创建一个Person对象p,然后定义一个指向Person::display()函数的指针`displayPtr`,最后通过`(p.*displayPtr)()`的方式调用该函数。注意,调用成员函数时要使用对象名和指针名的组合,中间需要加上`.`或`->`,这里使用`.`来访问成员函数。
相关推荐
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)