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

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

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

Восстановить пароль
Повторная активизация e-mail

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

Ответ
 
Опции темы Поиск в этой теме
Старый 12.09.2010, 12:31   #1
ignis_divine
 
Регистрация: 11.09.2010
Сообщений: 5
По умолчанию Статическая переменная

Доброе время суток.
Создана статическая bool переменная в private-секции класса, для определения вызывалась ли функция srand(time(0)) или нет. Определение переменной идет в конструкторе, использование в Matrix::fill_rand()
Компоновщик отказывается создавать проект. Заранее спасибо.

Matrix.h

Цитата:
#pragma once

class Matrix
{
private:
static bool rand_use;
bool result; // Result of summation or multiplying.
int x, y; // Number of strings and columns.
int** mx; // Matrix.
public:
Matrix(void); // Default constructor.
Matrix(int x, int y); // Usual constructor.
Matrix(const Matrix &); // Copy constructor
~Matrix(void); // Destructor.
void fill_hand(); // Filling the matrix by yourself.
void display(); // Displaying the content of object.
void fill_rand(); // Random filling of matrix.
bool summa(Matrix &, Matrix &); // Summation return correctness of execution.
bool multi(Matrix &, Matrix &); // Multiplying return correctness of execution.
};
Matrix.cpp

Цитата:
#include "Matrix.h"
#include "stdlib.h"
#include <iostream>
#include <ctime>

using namespace std;

Matrix::Matrix(void)
{
result = true;
}

Matrix::Matrix(int x1, int y1)
{
result = true;
rand_use = false;
x = x1;
y = y1;

mx = new int*[x];

for (int i = 0; i < x; i++)
{
mx[i] = new int[y];
for (int j = 0; j < y; j++)
{
mx[i][j] = 0 ;
}
cout<<endl;
}
}

Matrix::Matrix(const Matrix &from)
{
Matrix to(from.x, from.y);

to.x = from.x;
to.y = from.y;
to.result = from.result;

for (int i = 0; i < to.x; i++)
{
for (int j = 0; j < to.y; j++)
{
to.mx[i][j] = from.mx[i][j];
}
}
}

Matrix::~Matrix(void)
{
for (int i = 0; i < y; i++)
{
delete[] mx[i];
}
delete [] mx;

}

void Matrix::fill_rand()
{
if (!rand_use)
{
srand(time(0));
rand_use = true;
}
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
mx[i][j] = rand()%50;
}
}
}

void Matrix::fill_hand()
{
system("cls");
cout<<"Please enter the values of matrix[";
cout<<x<<"]"<<"["<<y<<"] in integer format.";
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
cout<<"\n"<<i<<" "<<j<<" element is: ";
cin>>mx[i][j];
}
}
}

void Matrix:isplay()
{
system("cls");
cout<<"Matrix ["<<x<<"]["<<y<<"]:";
for (int i = 0; i < x; i++)
{
cout<<endl;
for (int j = 0; j < y; j++)
{
cout<<" "<<mx[i][j];
}
}
cout<<endl;
system("pause");
}

bool Matrix::summa(Matrix& summand, Matrix& blank)
{

if (( x == summand.x) && (y == summand.y ))
{
for ( int i = 0; i < x; i++ )
for ( int j = 0; j < y; j++ )
{
blank.mx[i][j] = mx[i][j] + summand.mx[i][j];
}
return true;
}
else
{
return false;
}

}

bool Matrix::multi(Matrix& ier, Matrix & blank)
{
if (x == ier.y)
{
for ( int i = 0; i < x; i++ )
for ( int j = 0; j < y; j++ )
for ( int k = 0; k < ier.x; k++ )
return true;
}
else
{
if (y == ier.x)
{
for ( int i = 0; i < x; i++ )
for ( int j = 0; j < y; j++ )
for ( int k = 0; k < ier.x; k++ )
return true;
}
else
return false;
}
}
head.cpp

Цитата:
// Lab_work_1.cpp : Defines the entry point for the console application.
//
#include "Matrix.h"
#include "stdafx.h"
#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{
Matrix first(2,2);
Matrix second(2,2);

first.fill_rand();
second.fill_rand();

first.display();
second.display();

return 0;
}

ignis_divine вне форума Ответить с цитированием
Старый 12.09.2010, 13:54   #2
kogemrka
Форумчанин
 
Аватар для kogemrka
 
Регистрация: 08.01.2010
Сообщений: 165
По умолчанию

Напиши в Matrix.cpp

Код:
bool Matrix::rand_use;
для выделения памяти под переменную. Кстати, инициализировать её лучше там же, а не в конструкторе.

PS.
А давай всё-таки оформлять код в теге CODE, а не в теге QUOTE.
И ещё неплохо было бы копировать текст ошибки, которую выдаёт линковщик.

PPS.
Небольшое стилистическое замечание к коду. Почему ты пишешь
Код:
#include <ctime>
И в то же время пишешь
Код:
#include "stdlib.h"
В чём смысл?
Стоит писать оба подключения в стиле
Код:
#include <cstdlib>
#include <ctime>

Последний раз редактировалось kogemrka; 12.09.2010 в 14:05.
kogemrka вне форума Ответить с цитированием
Старый 12.09.2010, 14:30   #3
ignis_divine
 
Регистрация: 11.09.2010
Сообщений: 5
По умолчанию

Спасибо, проблема исчезла. А можешь объяснить разницу, почему в конструкторе не есть правильно?

Ошибки были следующие:

1>Matrix.obj : error LNK2001: unresolved external symbol "private: static bool Matrix::rand_use" (?rand_use@Matrix@@0_NA)
1>C:\Documents and Settings\user\Мои документы\Visual Studio 2008\Projects\Lab_work_1\Debug\Lab_ work_1.exe : fatal error LNK1120: 1 unresolved externals

... Написал и понял, при каждом создании нового объекта значение статич. переменной будет меняться.
ignis_divine вне форума Ответить с цитированием
Ответ


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



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Потерявшаяся переменная Кипящий чайник Общие вопросы C/C++ 10 11.07.2011 00:21
Переменная extern zgest Общие вопросы C/C++ 1 16.02.2010 14:28
Обнуляется переменная Hippie Помощь студентам 1 09.01.2010 20:22
qt4, win32 и статическая линковка. ASGAlex Qt и кроссплатформенное программирование С/С++ 3 09.06.2009 09:13