在本教程中,我们将讨论一个程序,以了解C ++中的构造函数。
构造函数是启动对象实例创建的类的成员函数。它们具有与父类相同的名称,并且没有任何返回类型。
#include <iostream>
using namespace std;
class construct {
public:
int a, b;
//默认构造函数
construct(){
a = 10;
b = 20;
}
};
int main(){
construct c;
cout << "a: " << c.a << endl
<< "b: " << c.b;
return 1;
}a: 10 b: 20
#include <iostream>
using namespace std;
class Point {
private:
int x, y;
public:
Point(int x1, int y1){
x = x1;
y = y1;
}
int getX(){
return x;
}
int getY(){
return y;
}
};
int main(){
Point p1(10, 15);
cout << "p1.x = " << p1.getX() << ", p1.y = " <<
p1.getY();
return 0;
}p1.x = 10, p1.y = 15