task4
Vector.hpp:
1 #pragma once 2 #include<bits/stdc++.h> 3 using namespace std; 4 template<typename T> 5 class Vector 6 { 7 private: 8 int size; 9 T* value; 10 public: 11 Vector(int s) :size{ s } { value = new T[s]; } 12 Vector(int s, T v); 13 Vector(const Vector<T> &v); 14 ~Vector() = default; 15 int get_size() const { return size; } 16 T& at(int n) { return value[n]; } 17 T& operator[](int n) const { return value[n]; } 18 template<typename T> 19 friend void output(Vector<T>); 20 }; 21 template<typename T> 22 Vector<T>::Vector(int s, T v) { 23 size = s; 24 value = new T[size]; 25 for (int i = 0; i < size; i++) 26 value[i] = v; 27 } 28 template<typename T> 29 Vector<T>::Vector(const Vector<T>& v) { 30 size = v.size; 31 value = new T[size]; 32 for (int i = 0; i < size; i++) 33 value[i] = v.value[i]; 34 } 35 template<typename T> 36 void output(Vector<T> v) { 37 for (int i = 0; i < v.size; i++) 38 cout << v.value[i] << ", "; 39 cout << "\b\b \n"; 40 }
Vector.cpp:
1 #include <iostream> 2 #include "Vector.hpp" 3 4 void test() { 5 using namespace std; 6 int n; 7 cin >> n; 8 9 Vector<double> x1(n); 10 for (auto i = 0; i < n; ++i) 11 x1.at(i) = i * 0.7; 12 output(x1); 13 Vector<int> x2(n, 42); 14 Vector<int> x3(x2); 15 output(x2); 16 output(x3); 17 x2.at(0) = 77; 18 output(x2); 19 x3[0] = 999; 20 output(x3); 21 } 22 23 int main() { 24 test(); 25 }
标签:int,value,Vector,实验,template,output,size From: https://www.cnblogs.com/zhouxv/p/16939198.html