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

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

Вернуться   Форум программистов > C/C++ программирование > Общие вопросы C/C++
Регистрация

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

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

Ответ
 
Опции темы Поиск в этой теме
Старый 08.10.2010, 18:41   #1
Lotles
Пользователь
 
Регистрация: 02.10.2010
Сообщений: 86
По умолчанию Ссылки

Hi all
Нельзя возвращать ссылку, если возвращаемое значение является локальной переменоой как здесь, потому что локальные переменные уничтожаются после выхода из функции
Код:
Fraction& Fraction::add(Fraction other) {
		Fraction fract;
    int lcd = lcm(den, other.den);
    int quot1 = lcd/den;
    int quot2 = lcd/other.den;
    fract.set(num * quot1 + other.num * quot2, lcd);
    fract.normalize();
    return fract;
}
Вот весь код, где возвращается ссылка из локальной переменной:
Код:
#include "stdafx.h"
#include "conio.h"
using namespace std;
class Fraction {
private:
    int num, den;   
public:
    Fraction() {num = 0; den = 0; normalize();} 
    Fraction(int n, int d) {set(n, d);}

    void set(int n, int d) {num = n; den = d; normalize();}
    int get_num()  {return num;}
    int get_den()  {return den;}
    Fraction add(Fraction other);
    Fraction mult(Fraction other);
private:
    void normalize(); 
    int gcf(int a, int b);     
    int lcm(int a, int b);    
};
int main(){
    Fraction f1, f2;
    Fraction f3(1, 2);

    cout << "The value of f1 is ";
    cout << f1.get_num() << "/";
    cout << f1.get_den() << endl;

    cout << "The value of f3 is ";
    cout << f3.get_num() << "/";
    cout << f3.get_den() << endl;
    return 0;
}
void Fraction::normalize(){
    if (den == 0 || num == 0) {
        num = 0;
        den = 1;
    }

    if (den < 0) {
        num *= -1;
        den *= -1;
    }

    int n = gcf(num, den);
    num = num / n;
    den = den / n;
}
int Fraction::gcf(int a, int b) {
    if (a % b == 0)
        return abs(b);
    else
        return gcf(b, a % b);
}
int Fraction::lcm(int a, int b){
    return (a / gcf(a, b)) * b;
}
Fraction& Fraction::add(Fraction other) {
		Fraction fract;
    int lcd = lcm(den, other.den);
    int quot1 = lcd/den;
    int quot2 = lcd/other.den;
    fract.set(num * quot1 + other.num * quot2, lcd);
    fract.normalize();
    return fract;
}
А если эту переменную Fraction fract; объявить глобально ?
Почему так нельзя?
Вот код, где возвращается ссылка для глобальной переменной
Код:
#include "stdafx.h"
#include "conio.h"
using namespace std;
class Fraction {
private:
    int num, den;   
public:
    Fraction() {num = 0; den = 0; normalize();} 
    Fraction(int n, int d) {set(n, d);}

    void set(int n, int d) {num = n; den = d; normalize();}
    int get_num()  {return num;}
    int get_den()  {return den;}
    Fraction add(Fraction other);
    Fraction mult(Fraction other);
private:
    void normalize(); 
    int gcf(int a, int b);     
    int lcm(int a, int b);    
};
		Fraction fract;
int main(){
    Fraction f1, f2;
    Fraction f3(1, 2);

    cout << "The value of f1 is ";
    cout << f1.get_num() << "/";
    cout << f1.get_den() << endl;

    cout << "The value of f3 is ";
    cout << f3.get_num() << "/";
    cout << f3.get_den() << endl;
    return 0;
}
void Fraction::normalize(){
    if (den == 0 || num == 0) {
        num = 0;
        den = 1;
    }

    if (den < 0) {
        num *= -1;
        den *= -1;
    }

    int n = gcf(num, den);
    num = num / n;
    den = den / n;
}
int Fraction::gcf(int a, int b) {
    if (a % b == 0)
        return abs(b);
    else
        return gcf(b, a % b);
}
int Fraction::lcm(int a, int b){
    return (a / gcf(a, b)) * b;
}
Fraction& Fraction::add(Fraction other) {
    int lcd = lcm(den, other.den);
    int quot1 = lcd/den;
    int quot2 = lcd/other.den;
    fract.set(num * quot1 + other.num * quot2, lcd);
    fract.normalize();
    return fract;
}

Последний раз редактировалось Lotles; 08.10.2010 в 18:43.
Lotles вне форума Ответить с цитированием
Старый 09.10.2010, 00:02   #2
Lotles
Пользователь
 
Регистрация: 02.10.2010
Сообщений: 86
По умолчанию

Тему можете удалить, забыл просто в определении функции add поставить ссылку
Lotles вне форума Ответить с цитированием
Ответ


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



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Ссылки segail Microsoft Office Excel 6 13.10.2009 22:16
Ссылки!!! саманта Помощь студентам 18 27.09.2008 21:38
Ссылки Принц HTML и CSS 1 31.05.2008 15:46