0

我想有一堂课:

class block {
public:
int NX,NY;

int A[][]; // I want the the dimension of A is from 1 to NX and 1 to NY, how do I do that?
};

实际上,我已经有了相应的 FORTRAN 代码,我想在 c++ 中拥有它,我相信通过正确使用构造函数,我将能够轻松地创建和复制对象,而不是像 FORTRAN 那样复制对象的每个组件。请教我如何做到这一点!谢谢!

module LinearSolution
    type LAE
        integer::N
        double precision,dimension(:,:),allocatable::A
        double precision,dimension(  :),allocatable::B
    contains
        procedure,nopass::RowReduction
    end type LAE
contains
    subroutine RowReduction
        double precision::C
        do k=1,N
            do i=k+1,N
                if(A(k,k)/=0) then
                    C=A(i,k)/A(k,k)
                    B(i)=B(i)-B(k)*C       !error: Statement Function is recursive
                    do j=k+1,N
                        A(i,j)=A(i,j)-A(k,j)*C   !error: Statement Function is recursive
                    end do
                end if
            end do
        end do

        do k=N,1,-1
            do i=k-1,1,-1
                if(A(k,k)/=0) then
                    C=A(i,k)/A(k,k)
                    B(i)=B(i)-B(k)*C  !error: Statement Function is recursive
                end if
            end do
        end do

        do k=1,N
            if(A(k,k)/=0) then
                B(k)=B(k)/A(k,k)  !error: Statement Function is recursive
            end if
        end do
    end subroutine RowReduction
end module LinearSolution

program TestLAE
    use LinearSolution  !fatal error: cant open module file LinearSolution.mod for reading
    type(LAE)::LAE1
    LAE1%N=3
    allocate(LAE1%B(1:N))
    allocate(LAE1%A(1:N,1:N))
    LAE1%B=(/1,1,1/)
    LAE1%A=(/2,0,0,0,2,0,0,0,2/)
    call LAE1%RowReduction
    print*, LAE1%B(1),LAE1%B(2),LAE1%B(3)
end program
4

2 回答 2

1

构造函数是你想要的吗?

class block {
public:
    int NX, NY;
    int **A;
    block(int nx, int ny){
        NX = nx;
        NY = ny;
        A = new int*[NX + 1];
        for(int x = 1; x <= NX; x++)
            A[x] = new int[NY + 1];
    }
    ~block(){
        for(int x = 1; x <= NX; x++)
            delete A[x];
        delete A;
    }
};
于 2013-05-02T13:48:32.090 回答
0

What you ask for is not possible with standard C++. In C++ the size of any array should be indexed with a constant. Even using the following syntax will give you an error.

const int NX=10;
const int NY=10;
int A[NX][NY];

One possibility is,

#define NX 10
#define NY 10
int A[NX][NY]; 
于 2013-05-02T13:50:29.860 回答