匿名对象做实参的案例java
时间: 2023-07-31 20:13:33 浏览: 106
下面是一个匿名对象做实参的案例Java代码:
```java
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public void print() {
System.out.println("(" + x + ", " + y + ")");
}
}
public class Main {
public static void func(Point p) {
p.print();
}
public static void main(String[] args) {
func(new Point(1, 2));
}
}
```
在这个例子中,我们定义了一个`Point`类,并且定义了一个`func`函数,该函数的参数是一个`Point`对象。在`main`函数中,我们调用`func`函数,并且将一个匿名的`Point`对象作为实参传入。
这个程序的输出结果是:
```
(1, 2)
```
可以看到,程序成功地创建了一个匿名的`Point`对象,并且将其作为实参传递给了`func`函数。`func`函数成功地打印出了这个匿名对象的坐标。
相关问题
匿名对象做实参的案例
下面是一个匿名对象做实参的案例:
```c++
#include <iostream>
using namespace std;
class Point {
public:
Point(int x = 0, int y = 0) : m_x(x), m_y(y) {}
void print() {
cout << "(" << m_x << ", " << m_y << ")" << endl;
}
private:
int m_x;
int m_y;
};
void func(Point p) {
p.print();
}
int main() {
func(Point(1, 2));
return 0;
}
```
在这个例子中,我们定义了一个`Point`类,并且定义了一个`func`函数,该函数的参数是一个`Point`对象。在`main`函数中,我们调用`func`函数,并且将一个匿名的`Point`对象作为实参传入。
这个程序的输出结果是:
```
(1, 2)
```
可以看到,程序成功地创建了一个匿名的`Point`对象,并且将其作为实参传递给了`func`函数。`func`函数成功地打印出了这个匿名对象的坐标。
c++将指向对象的指针作为函数参数 形参是对象指针 实参是什么
在 C++ 中,当我们将指向对象的指针作为函数参数时,形参是指函数定义中的变量,它是一个引用到对象的内存地址。实参则是当你调用函数时传递给这个形参的具体值,通常是一个对象的实例或者对象的指针。
例如:
```cpp
void displayStudent(Student* studentPtr) { // 函数声明,形参为 Student 类型的指针
cout << "Name: " << studentPtr->name << ", Age: " << studentPtr->age << endl;
}
// 调用函数时,实参可以是一个具体的 Student 对象
Student john{"John", 20};
displayStudent(&john); // &john 是 john 对象的指针
// 或者是一个 Student 指针变量
Student* ptr = new Student{"Alice", 25};
displayStudent(ptr);
```
在这个例子中,`&john` 和 `ptr` 都是实参,它们都指向了实际的学生对象。通过指针作为参数,函数可以处理任意类型的 Student 对象,体现了 C++ 的动态绑定特性。
阅读全文
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.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)