在Class Dim中我创建了数组G,我想将它传递给派生类PHYS_FIELD。它不是输出(0..9)而是给出(0..0)。我意识到它只是G的新副本,但我不知道如何正确地做到这一点。
#ifndef ARR1_H
#define ARR1_H
#include<iostream>
using namespace std;
template <class T> class arr1
{
public:
T* data;
size_t size;
arr1(const size_t isize)
{ size=isize;
data = new T[size];
}
T & operator ()(size_t const index)
{ return data[index]; }
};
#endif /*ARR1_H */
:
dim.h
#ifndef DIM_H
#define DIM_H
#include "arr1.h"
class DIM {
public:
DIM();
protected:
int N;
};
#endif /* DIM_H */
:
dim.cpp
#include "arr1.h"
#include "dim.h"
using namespace std;
DIM :: DIM()
{
N=10;
arr1<double> G(N);
for (int i=0; i<N; i++)
G(i)=i;
};
:
phys_field.h
#ifndef PHYS_FIELD_H
#define PHYS_FIELD_H
#include "dim.h"
#include "arr1.h"
class PHYS_FIELD : public DIM {
public:
PHYS_FIELD();
arr1<double> G;
};
#endif /* PHYS__FIELD_H */
:
phys_field.cpp
#include "dim.h"
#include "phys_field.h"
#include <arr1.h>
using namespace std;
PHYS_FIELD :: PHYS_FIELD(): G(N) {
cout<< " from phys_field.cpp "<<endl;
cout<<N<<endl;
for (int i=0; i<N ; i++)
cout<<i<<" "<<G(i)<<endl;
};
:
main.cpp
#include "dim.h"
#include "phys_field.h"
using namespace std;
int main(int argc, char* argv[]){
PHYS_FIELD *F= new PHYS_FIELD();
return 0;
}
:
{{1}}
答案 0 :(得分:0)
修改类arr1并添加一个接受零参数的构造函数(这样我们可以声明arr1 G,然后在DIM :: DIM构造函数中构建它
arr1()
{
}
类DIM:
protected:
arr1<double> G; //I've moved G from the constructor so that PHYS_FIELD can inherit it directly
DIM::DIM()
{
N=10;
G = arr1<double>(N);
for (int i=0; i<N; i++)
G(i)=i;
};
class PHYS_FIELD
从PHYS_FIELD标题中删除arr1<double> G;
,以便它不会隐藏从DIM继承的G
PHYS_FIELD::PHYS_FIELD() { //removed G(N)
cout << " from phys_field.cpp " << endl;
cout << N << endl;
for (int i=0; i<N; i++)
cout << i << " " << G(i) << endl;
};
这是你在找什么?