求大神 关于c++的,就是有参数的构造函数在定义中赋值出现错误,关于数组首地址和this指针
#include<iostream>#include<stdlib.h>usingnamespacestd;/*定义一个数组类Array,其私有数据成员为整型一维数组a[...
#include<iostream>#include<stdlib.h>using namespace std;/*定义一个数组类Array,其私有数据成员为整型一维数组a[10]。通过构造函数给a[10]赋初值。用Show函数显示a[10]的元素值。用成员函数重载运算符“+”,直接实现两个一维数组对应元素相加的运算。在主函数中定义数组a、b分别为:int a[10]={1,2,3,4,5,6,7,8,9,10}; int b[10]={4,5,6,7,8,9,10,11,12,13};用Array定义三个数组对象arr1(a)、arr2(b)、arr3,执行arr3=arr1+arr2运算,输出arr3的数组元素值。类似地,用友元函数重载运算符“+=”,实现复合赋值运算:arr1+=arr2,并输出arr1的元素值。*/class Array{public: Array(int *b); Array(); void show(); Array operator +(Array &b); friend Array operator +=(Array &a,Array &d);private: int *a;};Array::Array(int *b){ a=new int[10]; for(int i=0;i<10;i++) { a[i]=b[i]; }} Array::Array() { a = new int[10]; for (int i = 0; i < 10; i++) { a[i] = 0; } }void Array::show(){ for(int i=0;i<10;i++) cout<<a[i]<<' ';}Array Array::operator +(Array &b){ Array c(0); for(int i=0;i<10;i++) c.a[i]=a[i]+b.a[i]; return c;}Array operator +=(Array &a,Array &d){ for(int i=0;i<10;i++) a.a[i]+=d.a[i]; return a;}int main(){ int a[10]={1,2,3,4,5,6,7,8,9,10}; int b[10]={4,5,6,7,8,9,10,11,12,13}; Array arr1(a),arr2(b),arr3; arr3=arr1+arr2; arr3.show(); arr1+=arr2; arr1.show(); system("pause"); return 0;}
展开
1个回答
展开全部
需要定义拷贝构造函数和赋值函数
//ArrayOne.h
#pragma once
class ArrayOne {
public:
friend ArrayOne operator +=(const ArrayOne &a, const ArrayOne &d);
ArrayOne(const int *init);
ArrayOne();
~ArrayOne();
void show();
ArrayOne operator+(const ArrayOne &arrayOne)const;
ArrayOne operator=(const ArrayOne &arrayOne)const;
ArrayOne(const ArrayOne &arrayOne);
private:
int *vec;
};
ArrayOne operator +=(const ArrayOne &a, const ArrayOne &d);
//ArrayOne.cpp
#include "ArrayOne.h"
#include<iostream>
ArrayOne::ArrayOne(const int *init) {
vec = new int[10];
for (int i = 0; i < 10; i++) {
vec[i] = init[i];
}
}
ArrayOne::ArrayOne(const ArrayOne& arrayOne) {
vec = new int[10];
std::cout << "拷贝构造:"<<arrayOne.vec[0] << std::endl;
for (int i = 0; i < 10; i++)
vec[i] = arrayOne.vec[i];
}
ArrayOne::ArrayOne() {
std::cout << "默认构造" << std::endl;
vec = new int[10];
for (int i = 0; i < 10; i++)
vec[i] = 0;
}
ArrayOne::~ArrayOne() {
delete[] vec;
}
void ArrayOne::show() {
for (int i = 0; i < 10; i++)
std::cout<<vec[i] << ' ';
std::cout << std::endl;
}
ArrayOne ArrayOne::operator+(const ArrayOne &arrayOne)const {
ArrayOne sum;
for (int i = 0; i<10; i++)
sum.vec[i] = vec[i] + arrayOne.vec[i];
return sum;
}
ArrayOne ArrayOne::operator=(const ArrayOne &arrayOne)const {
for (int i = 0; i<10; i++)
vec[i] = vec[i] + arrayOne.vec[i];
return *this;
}
ArrayOne operator +=(const ArrayOne &a, const ArrayOne &d) {
for (int i = 0; i<10; i++)
a.vec[i] += d.vec[i];
return a;
}
//main.cpp
#include"ArrayOne.h"
int main() {
int a[10] = { 1,2,3,4,5,6,7,8,9,10 };
int b[10] = { 4,5,6,7,8,9,10,11,12,13 };
ArrayOne arr1(a), arr2(b),arr3;
arr3 = arr1 + arr2;
arr3.show();
arr1 += arr2;
arr1.show();
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询