Error overloaded operator must be a unary or binary operator has 3 parameters

I’m doing an assignment for my OOP class, and I am a little confused about the use of operator overloading. I’ve seen a few examples, but not using the operator<<, and I don’t quite get how this works. Here is the part I’m having trouble with:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

ID::ID()                                                                   
{                                                                                    
    SetName("#");
    
    SetAge(-1);

};  

ID::ID ( const char * name, int age )
{
    SetName(name);
    
    SetAge(age);
    
};

I have included the following in my public class declaration:

 
friend std::ostream &operator<<(std::ostream &, ID &);

And I need to be able to output what is passed into the constructor using the following:

1
2
3
ID p1, p2("Jane Doe", 25);
std::cout<< " p1 = " << p1 << 'n';
std::cout<< " p2 = " << p2 << 'n';

This should read:

1
2
p1 = #     -1
p2 = Jane Doe  25

I am confused about the operator overloading part, and right now I’m getting a linker error saying:

Undefined symbols for architecture x86_64:
«operator<<(std::ostream&, ID&)», referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Any help or a push in the right direction would be greatly appreciated. Thanks in advance.

**Update**
And now Im extra confused, I just realized that I’m not allowed to use ‘friend’, so I went back and changed the line in my header file to:

 
std::ostream &operator<<(std::ostream &output, ID &p1);

but now I’m getting «Overloaded ‘operator<<‘ must be a binary operator(has 3 parameters)»
What now?

Last edited on

#include <iostream>

using namespace std;

class ID
{
public:
ID::ID()
{
SetName(«#»);
SetAge(-1);
}

ID::ID(const char * name, int age)
{
SetName(name);
SetAge(age);
}

void SetName(const char* name)
{
strcpy(this->name,name);
}

void SetAge(int age)
{
this->age = age;
}

friend ostream& operator<<(ostream&, ID&);

private:
char name[BUFSIZ];
int age;
};

ostream& operator<<(ostream& cout, ID& id)
{
cout << id.name << ‘ ‘ << id.age << endl;
}

int main(void)
{
ID p1, p2(«Jane Doe», 25);

cout << » p1 = » << p1 << endl;
cout << » p2 = » << p2 << endl;

return 0;
}

[root@admin shm]# c++ op.cpp && ./a.out
p1 = # -1

p2 = Jane Doe 25

[root@admin shm]#

Thanks, but I’m still getting the same error as before. If I comment out the

 
friend std::ostream &operator<<(std::ostream &, ID &);

it works for p1, but when I get to p2 it doesn’t work there.

Could you show me your full source code here, then I could help you to figure it out ?

Last edited on

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#ifndef id_h                                                                               
#define id_h                                                                               

#include <iostream>  
#include <cstring>




class ID                                                                                   
{                                                                                        
public:                                                                                  
    
    ID();
    
    ID ( const char * name, int age );

    
    void SetName ( const char* );                                                          
    
    void SetAge ( int );                                                                   
    
    const char* GetName () const;                                                          
    
    int GetAge () const;  
    
    friend std::ostream &operator<<(std::ostream& cout, ID &);
 
    //std::ostream& operator << (std::ostream& os,const ID& p1);
    
    
    
private:                                                                                 
    
    char * name_;                                                                          
    
    int age_;                                                                              
    
    
};                                                                                         


#endif 

id.cpp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>                                                                    
#include "id.h" 
#include <cstring>
#include <iomanip>




ID::ID()                                                                   
{                                                                                    
    std::cout << "Hello default constructor." << std::endl; 
    
    
	SetName("#");
    
    SetAge(-1);

     std::cout << "nGoodbye default constructor" << std::endl; 
};  


ID::ID ( const char * name, int age )
{
    SetName(name);
    
    SetAge(age);
    
    ID p1;
    
    

    
    std::cout << name << age << std::endl;
    
};

void ID::SetName ( const char * name )                                                         
{                                                                                    
    //name = name_;
    
    strcpy(this->name_, name);
}     



void ID::SetAge ( int age )
{
    this->age_ = age;
}

main:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <cstdlib>                                                                         
#include <iostream>                                                                        
#include <iomanip>                                                                         
#include "id.h"                                                                           
//#include "id.cpp" // in lieu of makefile                                                 


const size_t arraySize = 10;                                                               
const size_t numDigits = 2;                                                                

//ID CopyCheck (ID id)  // pass in by value calls CC                                         
//{                                                                                          
//    ID x = id;  // initialization calls CC (NOT assignment!)                                 
//    return x;   // return by value calls CC                                                  
//}                                                                                          

int main()                                                                                 
{    
    
    ID p1; 
    ID p2("Jane Doe", 100);                                                          
    std::cout << " IDs after declaration:n";                                                
    std::cout << "  p1 = " << p1 << 'n';                                                    
    //std::cout << "  p2 = " << p2 << 'n';                                                    
    
    //p1.SetName("John Smith");                                                               
    //p1.SetAge(21);                                                                           
    //p2.SetName("Chris White");                                                                
    //p2.SetAge(21);                                                                           
    //std::cout << " IDs after Set:n";                                                        
    //std::cout << "  p1 = " << p1 << 'n';                                                    
    //std::cout << "  p2 = " << p2 << 'n';                                                    
    
    //p1 = CopyCheck(p2);                                                                      
    //std::cout << " IDs after p1 = CopyCheck(p2):n";                                         
    //std::cout << "  p1 = " << p1 << 'n';                                                    
    //std::cout << "  p2 = " << p2 << 'n'; 
    
    
    //ID p3 ("Assignment Check", 50);                                                          
    //p1 = p2 = p3;                                                                            
    //std::cout << " IDs after p1 = p2 = p3:n";                                               
    //std::cout << "  p1 = " << p1 << 'n';                                                    
    //std::cout << "  p2 = " << p2 << 'n';                                                    
    //std::cout << "  p3 = " << p3 << 'n';                                                    
    
   /* ID * idarray = new ID [arraySize];                                                       
    std::cout << " ID Array after declaration:n";                                           
    for (size_t i = 0; i < arraySize; ++i)                                                   
    {                                                                                        
        std::cout << "  id[" << std::setw(numDigits) << i << "] = " << idarray[i] << 'n';     
    } */                                                                                       
    
    
    //for (size_t i = 0; i < arraySize; ++i)                                                   
    //{                                                                                        
      //  idarray[i].SetName("A. B. Student");                                                   
        //idarray[i].SetAge(17 + i);                                                             
    //}                                                                                        
    //std::cout << " ID Array after Set:n";                                                   
    //for (size_t i = 0; i < arraySize; ++i)                                                   
    //{                                                                                        
      //  std::cout << "  id[" << std::setw(numDigits) << i << "] = " << idarray[i] << 'n';     
    //}                                                                                        
}  

You can pretty much ignore whatever is not revelant to this problem, I haven’t gotten very far with it yet, so I’m sure there’s still a lot for me to work out on my own if I can get past this part. The main was supplied by the instructor, as well as the prototypes for SetName, SetAge, GetName, GetAge, and variables name_ and age_, so none of that can be altered. My problem lies with the constructors, and operator overloading I believe. And I didn’t realize until after I posted, but I am not allowed to use ‘friend’ so I have to find a way to remove that. Assignment operator<< should be overloaded with type ID.

the problem is that char *name_ is a wild pointer.

you have already defined get/set interface for your private members of the ID class, so the keyword friend is utterly unnecessary.

BTW, i am not sure the purpose of the ID p1; statement in the second constructor -:)

Last edited on

Thank you very much for helping me. :)

Oops, the ID p1 line was an idea I had gone wrong, and I forgot to remove it.

So this means I should initialize char_ right?

Also, the
std::ostream& operator << (std::ostream& os,const ID& p1);
line still does not work, I get «Overloaded ‘operator<<‘ must be a binary operator(has 3 parameters)’ What does this mean? I tried adding another parameter, and it gave me the same message, only it said 4 parameters. I’m getting that line straight out of my book, so I don’t see why I’m getting this error.

you’d initialize char *_name definitely.

that means you give too much parameters, you got reverse tries, aha, the compiler tell you operator<< must be a BINARY operator, that means this operator overload method can only accept two parameters, try again to check it out!

Last edited on

Ok so I’m working on getting char_ * initialized, but I still don’t get the operator overload…there are only 2 parameters there, right? stream& os, and const ID& p1?

you must assure the declaration information in the header file must match the definition information in cpp file, could you paste the definition of std::ostream& operator << (std::ostream& os,const ID& p1) here ?

Last edited on

1
2
3
4
5
std::ostream &operator<<(std::ostream &output, ID &p1)
{
    output << p1.GetName() << "     " << p1.GetAge();
    return output;
}

.h file:
std::ostream &operator<<(std::ostream &output, ID &p1);

I’m getting the error in .h, same error message. It doesn’t even recognize it in .cpp

AHA!! Had the definition inside the definition of the class. Put it outside the class definition, and that error goes away, but it still doesn’t like my definition…..now I’m getting linker errors:

Undefined symbols for architecture x86_64:
«ID::GetName() const», referenced from:
operator<<(std::ostream&, ID&) in id.o
«ID::GetAge() const», referenced from:
operator<<(std::ostream&, ID&) in id.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I got it. std::ostream &operator<<(std::ostream& cout, ID &) must add friend keyword if within class definition. otherwise, omit it from the class definition.

I almost sure that you forgot add const keyword at the definition place of GetName() & GetAge().

Last edited on

Figured that one out…that was an oopsie on my part…still had them commented out. I think I can take it from here. Thank you so much for all your help, you probably saved me hours of headaches!

sure, good luck, you guy…

Topic archived. No new replies allowed.

У меня есть следующий шаблон класса:

    template <class T>
class Matrix {

public:
Matrix(size_t rows, size_t columns, const T elements = 0);// scalar multiplication
Matrix<T> operator*(const T& rhs){

Matrix<T> result(rows, columns);

for(size_t index = 0; index < rows * columns; ++index){
result.elements[index] = elements[index] * rhs;
}

return result;
}

Matrix <T> operator*(const T& lhs, const Matrix<T>& rhs);const size_t rows;
const size_t columns;private:

std::vector<T> elements;
};

и следующая реализация оператора *:

// scalar multiplication
template <class T>
Matrix<T> Matrix<T>::operator*(const T& lhs, const Matrix<T>& rhs){

Matrix<T> result(rhs.rows, rhs.columns);

for(size_t index = 0; index < rhs.rows * rhs.columns; ++index){
result.elements[index] = elements[index] * lhs;
}
return result;
}

когда я пытаюсь собрать Clang говорит: error: overloaded 'operator*' must be a unary or binary operator (has 3 parameters)|

И я не совсем понимаю, чего мне в этом не хватает. В общем, классы шаблонов доставляют мне трудности, когда дело доходит до перегрузки операторов, и я не знаю почему. Здесь, на SO, было несколько сообщений на эту тему, и я попробовал несколько вариантов кода, но ни один из них не работал.

2

Решение

Простой и достаточно эффективный способ решения этой проблемы заключается в следующем:

  1. Воплощать в жизнь Matrix& operator *=(SomeType const&) и аналогичные операции в первую очередь. Это мутирует операции, которые изменяют экземпляр класса, а затем возвращают ссылку на *this,

  2. Реализуйте другие операции как действующие друзья с точки зрения *=где аргумент lhs (обычно) принимается по значению, изменяется и возвращается.

Это, как правило, очень просто и часто более эффективно, чем начинать с operator* вместо operator*=,

Итак, вы будете иметь:

 template<class T, etc>
struct Matrix{
Matrix& operator*=(T const&);
Matrix& operator*=(Matrix const&);
Matrix& operator+=(Matrix const&);

который вы реализуете традиционно. Затем:

   friend Matrix operator*(T const& t, Matrix m){ m*=t; return m; }
friend Matrix operator*(Matrix m, T const& t){ m*=t; return m; }

friend Matrix operator*(Matrix lhs, Matrix const& rhs){ lhs*=rhs; return lhs; }
friend Matrix operator+(Matrix lhs, Matrix const& rhs){ lhs+=rhs; return lhs; }

и теперь вам нужно всего лишь реализовать несколько традиционных методов.

Эти friend операторы являются встроенными не шаблонными встроенными функциями, которые генерируются автоматически для каждого экземпляра шаблона Matrix.

Ваша непосредственная проблема заключалась в том, что ваш нестатический оператор фактически принял неявный this в дополнение к его двум явным параметрам, и бинарные операторы не могут принимать 3 аргумента.


Сложное и даже более эффективное решение включает технику, часто называемую «шаблоны выражений». Недостатком является то, что шаблоны выражений более сложны для написания и имеют несколько точек хрупкости по всему auto Ключевое слово и подобные ситуации.

В качестве примера:

Matrix m = m1 * m2 + m3 * m4 + m5 + m6;

Выражение шаблон будет делать выше только с одним распределением внутренних данных матрицы.

Мой код выше скопирует m1, умножьте результат на m2, Тогда это будет копировать m3затем умножьте это на m4, Тогда он будет складывать все, не делая дополнительных копий. Наконец, этот результат будет перенесен в m,

Таким образом, две матрицы будут созданы вместо 1 в случае шаблона выражения.

Более наивное решение (например, дизайн ОП) создаст 5 матриц вместо 2.

3

Другие решения

Вы декларируете Matrix <T> operator*(const T& lhs, const Matrix<T>& rhs); как функция-член, которая имеет неявный параметр thisВот почему компилятор жалуется, что «имеет 3 параметра».

Вы можете сделать это бесплатной функцией шаблона,

template <class T>
class Matrix {
...
template <class Z>
friend Matrix<Z> operator*(const Z& lhs, const Matrix<Z>& rhs);
...
};

а также

// scalar multiplication
template <class Z>
Matrix<Z> operator*(const Z& lhs, const Matrix<Z>& rhs){

Matrix<Z> result(rhs.rows, rhs.columns);

for(size_t index = 0; index < rhs.rows * rhs.columns; ++index){
result.elements[index] = elements[index] * lhs;
}
return result;
}

2

Ваша функция является функцией-членом. Функции-члены имеют скрытый параметр, указатель this.

Вы должны либо сделать свой оператор * не являющейся членом функции, либо вам нужно избавиться от одного из аргументов функции вашего оператора * (которая затем умножит данные в «this» на данные во входящей матрице<T>.)

2

Likkreannah

0 / 0 / 0

Регистрация: 08.02.2020

Сообщений: 17

1

Перегрузка операторов

28.03.2020, 14:57. Показов 5136. Ответов 7

Метки оператор, перегрузка оператора + (Все метки)


C++
1
2
3
4
int operator = (int left, int right)
 {
    return 9; 
 }

Почему не компилируется? В public класса

Untitled.cpp:29:6: error: overloaded ‘operator=’ must be a binary operator (has 3 parameters)
int operator = (int left, int right)
^
1 error generated.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



oleg-m1973

6574 / 4559 / 1843

Регистрация: 07.05.2019

Сообщений: 13,726

28.03.2020, 15:43

2

Лучший ответ Сообщение было отмечено Likkreannah как решение

Решение

Цитата
Сообщение от Likkreannah
Посмотреть сообщение

Почему не компилируется? В public класса

Потому что оператор присваивания для класса A должен выглядеть вот так

C++
1
A &operator = (int val)



1



Likkreannah

0 / 0 / 0

Регистрация: 08.02.2020

Сообщений: 17

29.03.2020, 11:36

 [ТС]

3

А почему оно не даёт 2 параметра добавить?
+ когда делаю так:

C++
1
XJ9.opr = XJ9.opr2; //opr и opr2 в public класса

и так:

C++
1
2
3
4
Crobot &operator = (int left, int hgvii)
 {
    cout << "htdyhdtyh";
 }

Ничего не выводится



0



oleg-m1973

6574 / 4559 / 1843

Регистрация: 07.05.2019

Сообщений: 13,726

29.03.2020, 11:42

4

Цитата
Сообщение от Likkreannah
Посмотреть сообщение

А почему оно не даёт 2 параметра добавить?
+ когда делаю так:

Потому что нельзя присвоить переменной сразу два значения
Подозреваю, здесь нужно так

C++
1
XJ9 = XJ9.opr2; //opr и opr2 в public класса
C++
1
2
3
4
5
Сrobot &operator = (int left)
 {
    cout << "htdyhdtyh";
return *this;
 }

Добавлено через 1 минуту
https://en.cppreference.com/w/… /operators



0



0 / 0 / 0

Регистрация: 08.02.2020

Сообщений: 17

29.03.2020, 11:52

 [ТС]

5

И всё равно не выводит cout



0



6574 / 4559 / 1843

Регистрация: 07.05.2019

Сообщений: 13,726

29.03.2020, 11:54

6

Цитата
Сообщение от Likkreannah
Посмотреть сообщение

И всё равно не выводит cout

Покажи весь код.



0



Likkreannah

0 / 0 / 0

Регистрация: 08.02.2020

Сообщений: 17

29.03.2020, 11:55

 [ТС]

7

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
using namespace std;
class Crobot
{
private:
string name;
int cureng;
int load;
 
public:
 int GetCurEng()
 {return cureng;}
 string GetName() 
 {return name;}
 int GetLoad()
 {return load;} 
 
 void SetCurEng(int indatas)
 {cureng = indatas;}
 void SetName(string indatas) 
 {name = indatas;};
 void SetLoad(int indatas)
 {load = indatas;}
 
 int opr;
 int opr2;
 
 //op +=, -=, (), --
 Crobot &operator = (int left)
 {
    cout << "htdyhdtyh";
    return *this;
 }
};
 
 
int main ()
{
Crobot XJ9;
XJ9.SetCurEng(100);
XJ9.SetName("XJ9");
XJ9.SetLoad(100);
 
cout << "Модель: " << XJ9.GetName() << endl;
cout << "Завантаженість: " << XJ9.GetLoad() << endl;
cout << "Заряд енергії: " << XJ9.GetCurEng() << endl;
 
XJ9.opr = XJ9.opr2;
 
return 0;
}



0



6574 / 4559 / 1843

Регистрация: 07.05.2019

Сообщений: 13,726

29.03.2020, 11:59

8

Цитата
Сообщение от Likkreannah
Посмотреть сообщение

XJ9.opr = XJ9.opr2;

XJ9 = XJ9.opr2;

Добавлено через 2 минуты
Иначе ты просто присваиваешь две переменных типа int.



1



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

29.03.2020, 11:59

8

У меня есть файл заголовка и .cpp файл. Я пытаюсь реализовать префикс и постфиксную перегрузку оператора, но я продолжаю получать эту ошибку при настройке перегрузки.

fraction.h

#ifndef FRACTION_H
#define FRACTION_H

#include <iostream>

using namespace std;

class Fraction 
{
   public:
      Fraction();
      Fraction(int, int);
      int getTop() {return m_top;}
      int getBottom() {return m_bottom;}
      void set(int t, int b) {m_top=t; m_bottom=b; reduce();
      }

   protected:
   private:
      void reduce();
      int gcf(int, int);

      int m_top;
      int m_bottom;
};

Fraction& operator ++ (Fraction);
Fraction operator++(Fraction, int);

#endif

main.cpp

#include <iostream>

using namespace std;
#include "fraction.h"

int main {
   cout << "The fraction is" << f;
   cout << "The output of ++f is " << (++f) << endl;
   cout << "The fraction is" << f;
   cout << "The output of f++ is " << (f++) << endl;
   cout << "The fraction is" << f;

   return 0;
}

Fraction& Fraction::operator ++ (Fraction){
   // Increment prefix
   m_top += m_bottom;
   return *this;
}

Fraction Fraction::operator ++ (Fraction, int){
   //Increment postfix
}

Вот две ошибки, которые я получаю:

 prefix error: "Parameter of overloaded post-increment operator must have type 'int' (not 'Fraction')"

postfix error: "Overloaded 'Operator++' must be a unary or binary operator (has 3 parameters)"

Является ли ошибка префикса фактической ошибкой с моей идеей? Я знаю, что это должно быть «int» для post-increment, но я пытаюсь сделать предварительный приращение. Я использую xcode.

26 окт. 2015, в 06:23

Поделиться

Источник

4 ответа

Вы объявили операторы вне класса как неклассовые функции

Fraction& operator ++ (Fraction);
Fraction operator++(Fraction, int);

однако тогда вы пытаетесь определить их как функции члена класса

Fraction& Fraction::operator ++ (Fraction){
   // Increment prefix
   m_top += m_bottom;
   return *this;
}

Fraction Fraction::operator ++ (Fraction, int){
   //Increment postfix
}

Либо объявить их как функции-члены класса следующим образом

class Fraction
{
public:
    Fraction & operator ++();
    Fraction operator ++( int );
    //...

И в этом случае определение примера оператора preincrement может выглядеть как

Fraction & Fraction::operator ++(){
   // Increment prefix
   m_top += m_bottom;
   return *this;
}

Или объявить их как функцию неклассов, которые являются друзьями класса, потому что они должны иметь доступ к частным членам данных класса

class Fraction
{
public:
    friend Fraction & operator ++( Fraction & );
    friend Fraction operator ++( Fraction &, int );
    //...

И в этом случае определение примера оператора preincrement может выглядеть как

Fraction & operator ++( Fraction &f ){
   // Increment prefix
   f.m_top += f.m_bottom;
   return f;
}

Vlad from Moscow
26 окт. 2015, в 07:13

Поделиться

Вы объявили функции свободными функциями

Fraction& operator ++ (Fraction);
Fraction operator++(Fraction, int);

но вы определяете их как функции-члены.

Fraction& Fraction::operator ++ (Fraction){ ... }
Fraction& Fraction::operator ++ (Fraction, int){ ... }

Поскольку функции-члены имеют неявный параметр this, ваши функции-члены имеют три параметра (this, Fraction и int).

Решите, хотите ли вы, чтобы функции были свободными или членами. Если вы хотите, чтобы они были свободными, определите их как свободные, а не как члены. Если вы хотите, чтобы они были участниками, объявите их как члены и настройте объявления, как указано в @crayzeewulf выше.

Raymond Chen
26 окт. 2015, в 07:23

Поделиться

Функция-член имеет неявный * этот указатель, который всегда указывает на объект класса, над которым работает функция-член. Параметр, который мы должны были явно указывать в версии функции друга (у которой не указан этот указатель), становится неявным * этим параметром в версии функции-члена.

Попробуйте сделать его нечленой функцией. Затем вы можете передать параметр
В противном случае удалите параметр.

Aditya Shekhawat
26 окт. 2015, в 07:06

Поделиться

    int main() {
    Fraction f;
    cout << "The fraction is" << f;
    cout << "The output of ++f is " << (++f) << endl;
    cout << "The fraction is" << f;
    cout << "The output of f++ is " << (f++) << endl;
    cout << "The fraction is" << f;


    return 0;
    }

    Fraction& Fraction::operator++ ()
    {
        // Increment prefix
        m_top += 1;
        return *this;
    }

    const Fraction Fraction::operator++ (int)
    {
        //Increment postfix
        Fraction temp = *this;
        ++(*this);
        return temp;
    }

    ostream& operator<<(ostream &os, const Fraction& f)
    {
        os << f.m_top << endl;
        return os;
    }

    Fraction::Fraction(const Fraction& f)
    {
        m_top = f.m_top;
        m_bottom = f.m_bottom;
    }

    Fraction::Fraction(int t, int b) :m_top(t), m_bottom(b){}
    Fraction::Fraction() : m_top(1), m_bottom(1){}


     class Fraction
    {
    public:
        Fraction();
        Fraction(int, int);
        Fraction(const Fraction& f);
        int getTop() { return m_top; }
        int getBottom() { return m_bottom; }
        void set(int t, int b) {
            m_top = t; m_bottom = b; reduce();
        }
        Fraction& operator ++ ();
        const Fraction operator++(int);

        friend ostream& operator<<(ostream &os,const Fraction& f);

        protected:
        private:
        void reduce();
        int gcf(int, int);

        int m_top;
        int m_bottom;
        };
        #endif

xiang yang
26 окт. 2015, в 06:44

Поделиться

Ещё вопросы

  • 0Разделить QString на — (тире) символ, доступ к элементу списка
  • 0Использование group by для возврата строки с max ()
  • 1Просмотр миниатюр в Android
  • 0Позиция диалога со смещением не работает
  • 1Как обернуть Hibernate сессионный API, чтобы избежать «непроверенных» предупреждений об обобщениях
  • 1Добавить таймер для изображений в javafx
  • 0MySQL Join Query на возрастной диапазон
  • 0PHP, MYSQL: выбрать внутри цикла Loop?
  • 0Как ограничить текст только 3 предложениями?
  • 1Отключить текст под изображением штрих-кода в Code39Bean
  • 1Как использовать служебное свойство в маршруте?
  • 1Сбой установки AWS EB CLI с «python setup.py egg_info» завершился ошибкой с кодом ошибки 1 «
  • 0Проблема с компиляцией функции, которая возвращает строку &
  • 0Как отсортировать массив в C ++ определенным образом
  • 1Как совместить вкладки Android с другими представлениями?
  • 1Python заменяет javascript двойными кавычками в коде javascript
  • 0Как не вызывать директиву каждый раз, когда я перезагружаю страницу
  • 0Как переписать url-encoded-base64 с помощью .htaccess
  • 0показ одной опции в один div после двух выбранных выпадающих
  • 0Инициализация / Назначение переменных члена класса другим переменным члена класса
  • 0Инициализация колоды с использованием Юникода
  • 1Проверка MVC с другой ViewModel
  • 1Прослушивание, когда жест происходит на конкретном объекте на экране
  • 0Могу ли я получить шаблонный генератор равномерного распределения, который будет работать для любого числового типа?
  • 1Как заменить функцию в Python?
  • 0получить тело письма imap_fetchbody ()
  • 0Форматирование входных значений, но с трудностями при обновлении модели
  • 0Выбор конкретного тега в библиотеке Jquery
  • 0Как сделать несколько запросов в Spring Batch (в частности, используйте LAST_INSERT_ID ())
  • 1Проверка пароля — добавление дополнительных требований
  • 0Проблемы с созданием 100% высоты с использованием display: table-cell в Firefox
  • 0Переменные PHP в вопросе JavaScript
  • 1Количество клиентов сокетов, подключенных к серверу
  • 0CUDA и C ++ простой проект
  • 1Определение свойств UserControl и их привязка в Windows Phone
  • 1Проблема SAXParser при получении значения тега с символом &
  • 1Является ли формат файла конфигурации DRBD стандартным?
  • 0Как искать структуру JSON
  • 0Как поставить условие на связанные события?
  • 1Android — как улучшить HorizontalScrollView, который имеет много просмотров / изображений внутри
  • 1ModuleNotFoundError: нет модуля с именем tenensflow.contrib.framework
  • 0Mysql агрегированная сумма построчно [дубликаты]
  • 0Утечки памяти, когда мой код компилируется GCC
  • 0нет ошибки вызова соответствующей функции
  • 0Как показать-скрыть именованное представление в angular-ui-router
  • 1Две функции addEventListener на двух разных элементах
  • 1Добавить текстовое поле в нижний колонтитул gridview
  • 0Как сделать приложение RequireJS модульным, т.е. загружать файлы на ходу, а не сразу

Сообщество Overcoder

Понравилась статья? Поделить с друзьями:
  • Error penumerator getdefaultaudioendpoint
  • Error outputting keys and certificates openssl
  • Error output so disabling automatic redirect
  • Error output processing capture one
  • Error out of video memory trying to allocate a texture pubg