如何在 C++ 中“返回一个对象”?
对象是类的实例。只在创建对象时才会分配内存,但在定义类时不会分配内存。
可以使用 return 关键字通过函数返回一个对象。展示此内容的程序如下 −
示例
#include <iostream>
using namespace std;
class Point {
private:
int x;
int y;
public:
Point(int x1 = 0, int y1 = 0) {
x = x1;
y = y1;
}
Point addPoint(Point p) {
Point temp;
temp.x = x + p.x;
temp.y = y + p.y;
return temp;
}
void display() {
cout<<"x = "<< x <<"\n";
cout<<"y = "<< y <<"\n";
}
};
int main() {
Point p1(5,3);
Point p2(12,6);
Point p3;
cout<<"Point 1\n";
p1.display();
cout<<"Point 2\n";
p2.display();
p3 = p1.addPoint(p2);
cout<<"The sum of the two points is:\n";
p3.display();
return 0;
}输出
上述程序的输出如下所示。
Point 1 x = 5 y = 3 Point 2 x = 12 y = 6 The sum of the two points is: x = 17 y = 9
现在,让我们了解一下上述程序。
类 Point 具有两个数据成员,即 x 和 y。它具有一个参数化构造函数和 2 个成员函数。函数 addPoint() 添加两个 Point 值,并返回存储和值的临时对象。函数 display() 打印 x 和 y 的值。此内容的代码片段如下所示。
class Point {
private:
int x;
int y;
public:
Point(int x1 = 0, int y1 = 0) {
x = x1;
y = y1;
}
Point addPoint(Point p) {
Point temp;
temp.x = x + p.x;
temp.y = y + p.y;
return temp;
}
void display() {
cout<<"x = "<< x <<"\n";
cout<<"y = "<< y <<"\n";
}
};在函数 main() 中,创建了类的 3 个对象。首先显示 p1 和 p2 的值。然后,通过调用函数 addPoint() 找到 p1 和 p2 中值的总和并存储在 p3 中。显示 p3 的值。此内容的代码片段如下所示。
Point p1(5,3); Point p2(12,6); Point p3; cout<<"Point 1\n"; p1.display(); cout<<"Point 2\n"; p2.display(); p3 = p1.addPoint(p2); cout<<"The sum of the two points is:\n"; p3.display();
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP