Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > IT форум > Помощь студентам
Регистрация

Восстановить пароль

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 27.12.2008, 17:56   #11
challengerr
Участник клуба
 
Аватар для challengerr
 
Регистрация: 30.07.2008
Сообщений: 1,609
По умолчанию

Не умеешь разбивать файлы? Это можно сделать в простом блокноте используя лишь копи-паст
Описание класса матрицы запихиваешь в файл matrix.h
Методы класса запихиваешь в файл matrix.cpp, указывая в начале #include "matrix.h"
Описание функции print_vector запихиваешь в файл vector.h
Тело функции print_vector запихиваешь в файл vector.cpp, указывая в начале #include "vector.h"
Функцию main запихиваешь в файл main.cpp, указывая в начале #include "matrix.h" и #include "vector.h" Всякие стандартные инклуды можно сюда же.

Затем создаешь пустой проект. Добавляешь все указанные файлы в проект. Переходишь в файл main.cpp. Нажимаешь кнопку Compile

Если через командную строку, то
cl main.cpp matrix.cpp vector.cpp /nologo /W3 /GX /O2 /D 'WIN32' /D 'NDEBUG' /D '_CONSOLE' /D '_MBCS' /YX /FD /c

link main.obj matrix.obj vector.obj kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib ws2_32.lib /nologo /subsystem:console /machine:I386
"SPACE.THE FINAL FRONTIER.This's a voyage of starship Enterprise. It's 5-year mission to explore strange new worlds,to seek out new life and civilizations,to boldly go where no man has gone before"
challengerr вне форума Ответить с цитированием
Старый 27.12.2008, 22:52   #12
xsix
Пользователь
 
Аватар для xsix
 
Регистрация: 27.12.2008
Сообщений: 20
По умолчанию

vector.cpp записал так:
Код:
#include "vector.h"

vector::vector(void)
{
void print_vector(V m, int sz)
{
        int i;
        for (i=0 ; i<sz; i++)
        {
                cout << m[i] <<"  ";

        }
        cout <<"\n";
}
vector.h:
Код:
#pragma once

class vector
{
public:
	vector(void);
	~vector(void);
	void print_vector(V m, int sz)
};
main.cpp:
Код:
#include "stdafx.h"
#include "matrix.h"
#include "vector.h"

	void main()
{
        int x,y;
        cin >> x; // строк
        cin >> y; // столбцов
        matrix<int> tr(x,y);
        double* res;
        tr.random();
        tr.print();
        res = tr.sr();
        cout<<"\n";
        print_vector(res,tr.getcol());
	return 0;
}
matrix.cpp:
Код:
#include "StdAfx.h"
#include "matrix.h"

matrix::matrix(int rows, int columns)
{
        int i;
        if (rows>0 && columns >0)
        {
                m=new T*[rows];
                for (i=0;i<rows;i++)
                {
                        m[i]=new T[columns];
                }
        }
        row=rows;
        col=columns;

}

matrix::~matrix()
{
        int i;
        for (i=0;i<row;i++)
                {
                        delete[] m[i];
                }
        
        delete[] m;

}
matrix<T>::manually_set()
{
        int i,j;
        for (i=0;i<row;i++)
        {
                for (j=0;j<col;j++)
                {
                        cin >> m[i][j];
                }
                        
        }
}
matrix<T>::random()
{
        int i,j;
        srand (time(NULL));

        for (i=0 ; i<row; i++)  
                for (j=0; j<col;j++)            
                        m[i][j]=rand()%10;

}
int matrix<T>::getcol()
{
        return(col);
}

template <class T>
int matrix<T>::getrow()
{
        return(row);
}
double* matrix<T>::sr()
{
        double* result;
        int i,j,l;
        double sum;

        result=new double[col];
        l=0;

        for(i=0;i<col;i++)
        {
                sum=0;
                for (j=0;j<row;j++)
                {
                        sum+=m[j][i];
                }
                sum/=row;
                result[l]=sum;
                l++;
        }

        return(result);
}
matrix<T>::set_from_array( T* k)
{
        int i,j,l;

        for (i=0,l=0;i<row;i++)
        {
                for (j=0;j<col;j++)
                {
                        m[i][j]=k[l];                   
                        l++;
                }
                        
        }
}
matrix<T>::set_value(int y1, int x1, T value)
{
        m[y1][x1]=value;
}
matrix<T>::get_by_index(int i,int j)
{
        if (i>=0 && j>=0 && i<row && j<col)
        {
                return(m[i][j]);
        }
        else
                return(-1);
}
matrix<T>::print()
{
        int i,j;
        for (i=0;i<row;i++)
        {
                for (j=0;j<col;j++)
                {
                        cout << m[i][j] << "  ";
                }
                cout << "\n";
                        
        }
}
matrix<T>::swap_values(int y1,int x1, int y2,int x2)
{
        T temp;
        temp=m[y1][x1];
        m[y1][x1]=m[y2][x2];
        m[y2][x2]=temp;
}
И наконец:

matrix.h:
Код:
#pragma once

class matrix
{
public:

    matrix(int rows, int columns);
    ~matrix();
    manually_set();
    print();
    random();
    set_from_array(T* k);           
    T get_by_index(int y,int x);
    swap_values(int y1,int x1, int y2,int x2);
    set_value(int y1, int x1, T value);
    int getcol();
    int getrow();
    double* sr();

   private:
                T** m;
                int row;
                int col;


};
Вроде-бы всё правильно, но при компиляции выдаёт ошибку... В чём проблема, не знаю.

Последний раз редактировалось xsix; 28.12.2008 в 12:44.
xsix вне форума Ответить с цитированием
Старый 28.12.2008, 01:59   #13
xsix
Пользователь
 
Аватар для xsix
 
Регистрация: 27.12.2008
Сообщений: 20
По умолчанию

Ну где я допустил ошибку?
xsix вне форума Ответить с цитированием
Старый 28.12.2008, 12:14   #14
xsix
Пользователь
 
Аватар для xsix
 
Регистрация: 27.12.2008
Сообщений: 20
По умолчанию

Пожалуйста проверьте... Правильно-ли написан код.?1
xsix вне форума Ответить с цитированием
Старый 28.12.2008, 13:43   #15
xsix
Пользователь
 
Аватар для xsix
 
Регистрация: 27.12.2008
Сообщений: 20
По умолчанию

vector.cpp и vector.h выдают затруднения, в Visual Studio я их создал как класс. А challengerr говорит что класса вектора как такового нет. Вообщем я не знаю как поступить, мне нужно точно разобраться с кодом для vector.cpp и vector.h. Народ, пожалуйста, откликнитесь.

В какой роли выступает здесь вектор?

Последний раз редактировалось xsix; 28.12.2008 в 13:46.
xsix вне форума Ответить с цитированием
Старый 28.12.2008, 14:40   #16
challengerr
Участник клуба
 
Аватар для challengerr
 
Регистрация: 30.07.2008
Сообщений: 1,609
По умолчанию

1. Какой смысл создавать класс вектора из одной функции? Конструктор и деструктор не нужны, т.к. у тебя нет никаких данных внутри класса vector.
2. Зачем ты удалил template <class T> перед class matrix? Нужно вернуть
Если ты указываешь внутри класса вектор функцию void print_vector(V m, int sz), то объяви template <class V> перед class vector. В ЯЗЫКЕ С++ НЕТ ТИПОВ T и V!!!

3. Перед void print_vector(V m, int sz) надо удалить
vector::vector(void)
{
Это незакрытая фигурная скобка.

4. Перед описанием методов класса матрица верни template <class T>. Объясни из каких соображений ты удалил template <class T>?
"SPACE.THE FINAL FRONTIER.This's a voyage of starship Enterprise. It's 5-year mission to explore strange new worlds,to seek out new life and civilizations,to boldly go where no man has gone before"
challengerr вне форума Ответить с цитированием
Старый 28.12.2008, 14:54   #17
xsix
Пользователь
 
Аватар для xsix
 
Регистрация: 27.12.2008
Сообщений: 20
По умолчанию

удалил template <class T> т.к не знал что это такое, вообщем не встречал и подумал это ваша вставка. Помоги пожалуйста описать всё по отдельности... А то я этот вопрос так и не решу!

А
Код:
 #include <windows.h>
             #include <iostream.h>
            #include <time.h>
в main кидать?

Последний раз редактировалось xsix; 28.12.2008 в 15:16.
xsix вне форума Ответить с цитированием
Старый 28.12.2008, 16:27   #18
challengerr
Участник клуба
 
Аватар для challengerr
 
Регистрация: 30.07.2008
Сообщений: 1,609
По умолчанию

Код:
#include <windows.h>
#include <iostream.h>
#include <time.h>
в stdafx.h (только проверь нет ли их там уже)

И добавь описание #include stdafx.h в vector.h
"SPACE.THE FINAL FRONTIER.This's a voyage of starship Enterprise. It's 5-year mission to explore strange new worlds,to seek out new life and civilizations,to boldly go where no man has gone before"
challengerr вне форума Ответить с цитированием
Старый 28.12.2008, 20:06   #19
xsix
Пользователь
 
Аватар для xsix
 
Регистрация: 27.12.2008
Сообщений: 20
По умолчанию

Всё сделал как сказал, но при компиляции выдаёт 25 ошибок О_о. Вот некоторые их них
Код:
see declaration of 'matrix<T>::matrix'
1>        definition
1>        'matrix::matrix(int,int)'
1>        existing declarations
1>        'matrix<T>::matrix(int,int)'
1>e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.cpp(32) : error C2244: 'matrix<T>::~matrix' : unable to match function definition to an existing declaration
1>        e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.h(9) : see declaration of 'matrix<T>::~matrix'
1>        definition
1>        'matrix::~matrix(void)'
1>        existing declarations
1>        'matrix<T>::~matrix(void)'e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.h(10) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>        e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.h(27) : see reference to class template instantiation 'matrix<T>' being compiled
1>e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.h(10) : warning C4183: 'manually_set': missing return type; assumed to be a member function returning 'int'
1>e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.h(11) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.h(11) : warning C4183: 'print': missing return type; assumed to be a member function returning 'int'
1>e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.h(12) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.h(12) : warning C4183: 'random': missing return type; assumed to be a member function returning 'int'
1>e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.h(13) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.h(13) : warning C4183: 'set_from_array': missing return type; assumed to be a member function returning 'int'
1>e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.h(15) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.h(15) : warning C4183: 'swap_values': missing return type; assumed to be a member function returning 'int'
1>e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.h(16) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.h(16) : warning C4183: 'set_value': missing return type; assumed to be a member function returning 'int'
1>e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.cpp(20) : error C2244: 'matrix<T>::matrix' : unable to match function definition to an existing declaration
1>        e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.h(8) : see declaration of 'matrix<T>::matrix'
1>        definition
1>        'matrix::matrix(int,int)'
1>        existing declarations
1>        'matrix<T>::matrix(int,int)'
1>e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.cpp(32) : error C2244: 'matrix<T>::~matrix' : unable to match function definition to an existing declaration
1>        e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.h(9) : see declaration of 'matrix<T>::~matrix'
1>        definition
1>        'matrix::~matrix(void)'
1>        existing declarations
1>        'matrix<T>::~matrix(void)'
e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.h(10) : warning C4183: 'manually_set': missing return type; assumed to be a member function returning 'int'
1>e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.h(11) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.h(11) : warning C4183: 'print': missing return type; assumed to be a member function returning 'int'
1>e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.h(12) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.h(12) : warning C4183: 'random': missing return type; assumed to be a member function returning 'int'
1>e:\documents and settings\coding\рабочий стол\c++\n2\n2\matrix.h(13) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Он ругается насчёт методов...... И что-то насчёт целого типа данных int. Что такое?
И ещё, template <class T> перед каждым методом над добавлять в matrix.cpp или только перед классом? Извините, я наверное вас достал.

Последний раз редактировалось xsix; 28.12.2008 в 20:14.
xsix вне форума Ответить с цитированием
Старый 28.12.2008, 22:16   #20
challengerr
Участник клуба
 
Аватар для challengerr
 
Регистрация: 30.07.2008
Сообщений: 1,609
По умолчанию

Перед каждым методом, перед конструктором и деструктором и перед самим классом.

ОШИБКА 1:
Код:
see declaration of 'matrix<T>::matrix'
1>        definition
1>        'matrix::matrix(int,int)'
1>        existing declarations
1>        'matrix<T>::matrix(int,int)'
Он говорит тебе, что объявления не соответствуют!!!
В matrix.cpp вместо
Код:
matrix::matrix(int rows, int columns)
должно быть
Код:
template <class T>
matrix<T>::matrix(int rows, int columns)
Последующие ошибки возникли по той же причине и исправляются так же.
"SPACE.THE FINAL FRONTIER.This's a voyage of starship Enterprise. It's 5-year mission to explore strange new worlds,to seek out new life and civilizations,to boldly go where no man has gone before"
challengerr вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Двумерный массив Анжелика Помощь студентам 3 29.12.2008 21:23
Двумерный массив... Seriy8888 Паскаль, Turbo Pascal, PascalABC.NET 1 24.12.2008 21:26
Двумерный массив в С++ Draid Помощь студентам 2 07.03.2008 22:06
Двумерный массив help Imperceptible Паскаль, Turbo Pascal, PascalABC.NET 25 02.03.2007 20:00