定义多维的点模板类,任意数据类型

本文介绍了一个通用的模板类Point的实现方法,该类能够用于多种数据类型,并支持不同维度的坐标点操作。通过使用assert断言确保了数组索引的有效性,同时提供了重载的流插入运算符来方便地打印坐标点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <assert.h>
using namespace std;
template <class type, int dim>
class Point{
public:
Point();
Point(type coords[dim]){
     for(int idx = 0; idx < dim; idx ++){
      _coords[idx] = coords[idx];
    }
}
type &operator [] (int idx){
    assert ( idx < dim && idx >= 0);
    return _coords[idx];
}
type operator [] (int idx) const{
        assert ( idx < dim && idx >= 0);
        return _coords[idx];
}
private:
type _coords[dim];
};
template <class type, int dim>
inline
ostream & operator << (ostream & os,  const Point<type, dim> &pt){
os << "(";
for (int idx = 0; idx < dim -1; idx ++)
    os << pt[idx] << " , ";
os << pt[dim -1];
os << ")";
}
//example
int main() {
    cout  << "test\n";
    float t_f[3] = {0.0f, 0.1f,0.2f};
    Point<float, 3> t_pt(t_f);
    cout << t_pt; 
    return 0;
}

//result
简单测试运行结果展示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值