c++ 构造

2023-12-05

#include <iostream>
using namespace std;

class Coordinate
{
public:
// 无参构造函数
// 如果创建一个类你没有写任何构造函数,则系统自动生成默认的构造函数,函数为空,什么都不干
// 如果自己显示定义了一个构造函数,则不会调用系统的构造函数
Coordinate()
{
c_x = "0";
c_y = "0";
}

// 一般构造函数
Coordinate(const std::string x, const std::string y):c_x(x), c_y(y){}   //列表初始化
// 一般构造函数可以有多个,创建对象时根据传入的参数不同调用不同的构造函数

Coordinate(const Coordinate& c)
{
// 复制对象c中的数据成员
c_x = c.c_x;
c_y = c.c_y;
}

// 等号运算符重载
Coordinate& operator= (const Coordinate& rhs)
{
// 首先检测等号右边的是否就是等号左边的对象本身,如果是,直接返回即可
if(this == &rhs)
return* this;
// 复制等号右边的成员到左边的对象中
this->c_x = rhs.c_x;
this->c_y = rhs.c_y;
return* this;
}

std::string get_x()
{
return c_x;
}

std::string get_y()
{
return c_y;
}

private:
std::string c_x;
std::string c_y;
};

int main()
{
Coordinate c3("1.0", "2.0");
cout<<"c3 = "<<"("<<c3.get_x()<<", "<<c3.get_y()<<")"<<endl;
return 0;
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

c++ 构造 的相关文章

随机推荐