c++ self reference
조회수 369회
코드 작성하고 원하는 입출력값도 제대로 나오는데 코드를 제출만 하면 런타임 오류가 뜹니다 ㅠㅠ 어디가 문제인지 모르겠어요 ㅠㅠ 수정 좀 도와주세요 ㅠㅠ
입력: 2 3 1 1 1 1 출력: 12.00 8.49
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
class Vector{
// 이 부분을 구현한다.
private:
double* X;
int n;
public:
Vector(int n);
~Vector();
void read();
double norm(int p);
Vector(const Vector& vec);
Vector& add(const Vector& vec) {
this -> n = vec.n;
for(int i = 0; i < n; i++){
this -> X[i] += vec.X[i];
}
return *this;
}
Vector& mul(const double c) {
this -> n = c;
for(int i = 0; i < n; i++) {
this -> X[i] *= c;
}
return *this;
}
private:
double l1_norm();
double l2_norm();
};
Vector::Vector(int n) : n(n) {
X = new double[n];
}
Vector:: ~Vector() {
delete[] X;
}
void Vector::read() {
for(int i = 0; i < n; i++)
cin >> X[i];
}
double Vector::norm(int p) {
if(p == 1) return l1_norm();
return l2_norm();
}
Vector::Vector(const Vector& vec) {
this -> n = vec.n;
X = new double[n];
for(int i = 0; i < n; i++){
this -> X[i] = vec.X[i];
}
}
double Vector::l1_norm() {
double ret = 0.0;
for(int i = 0; i < n; i++)
ret += abs(X[i]);
return ret;
}
double Vector::l2_norm() {
double ret = 0.0;
for(int i = 0; i < n; i++)
ret += pow(X[i], 2.0);
return sqrt(ret);
}
int main(){
int n;
double c;
cin >> n >> c;
Vector& A = *(new Vector(n)); // 포인터 대신 참조자로 받음
Vector& B = *(new Vector(n));
A.read();
B.read();
Vector D = A.add(B).mul(c); // D = (A+B)*C
delete &A;
delete &B; // 깊은 복사가 제대로 되었는지 확인하기 위해 원본 삭제
cout << fixed << setprecision(2);
cout << D.norm(1) << endl;
cout << D.norm(2) << endl;
return 0;
}
-
(•́ ✖ •̀)
알 수 없는 사용자
댓글 입력