2015-07-27 3 views
-1

Я создаю программу, которая имитирует телефонные звонки и текстовые сообщения. Я пытаюсь передать информацию с объекта класса «phone» на мои функции dialNum и txtNum до cout, когда пользователь назначает два телефонных номера как исходящие и принимающие телефоны, но мне трудно понять, что делать.Передача параметров объекта в функции C++

Это мой код до сих пор:

#ifndef PHONENUMBER_H 
#define PHONENUMBER_H 

#include <iostream> 
#include <iomanip> 

using namespace std; 

class PhoneNumber { 
public: 

    PhoneNumber(const PhoneNumber &); 
    friend ostream &operator<<(ostream&, const PhoneNumber &); 
    friend istream &operator>>(istream&, PhoneNumber &); 
    void dialNum(); 
    void txtNum(); 
    void displaySummary(); 
    operator int() const {return phonenumberval;} 
// Constructor(int, int); 

private: 
    char areaCode[ 5 ]; // 3-digit area code and null 
    char exchange[ 5 ]; // 3-digit exchange and null 
    char line[ 5 ]; // 4-digit line and null 
    int phonenumberval; 
    static int ntext; 
    static int nlive; 

}; // end class PhoneNumber 

#endif 


PhoneNumber::PhoneNumber (const PhoneNumber &phone1){ 

    phonenumberval = phone1. PhoneNumber; 
} 

ostream &operator<<(ostream &output, const PhoneNumber &num) 
{ 
    output << "(" << num.areaCode << ")" << num. exchange << "-" << num.line; 

    return output; // enables cout << a << b << c; 
} // end function operator<< 

istream &operator>>(istream &input, PhoneNumber &num) 
{ 
    input.ignore(0); 
    input >> setw(4) >> num.areaCode; 
    input.ignore(1); // skip (and space 
    input >> setw(4) >> num.exchange; 
    input.ignore(); 
    input >> setw(5) >> num.line; // input line 

    return input; 
} 

void PhoneNumber::dialNum(){ 
    int num1; 
    int num2; 
    cout << "Enter originating phone: " << endl; 
    cin >> num1; 
    cout << "Enter recieving phone: " << endl; 
    cin >> num2; 
    cout << " Calling number " << num2 <<"...call made."<< endl; 
    cout << "The const int phonenumberval = " << phonenumberval; 
} 

void PhoneNumber::txtNum(){ 
    string txt; 
    int textphone1; 
    int textphone2; 

    cout << "Enter orginating phone: " << endl; 
    cin >> textphone1; 
    cout << "Enter receiving phone: " << endl; 
    cin >> textphone2; 
    cout << "Enter text message to send." << endl; 
    cin >> string txt; 
    cout << "Sending message to " << textphone2 << " .....message sent." <<  endl; 
} 

void PhoneNumber::displaySummary(int a, int b){ 
    nlive = int b; 
    ntext = int a; 

    cout << "You made " << nlive << " calls and " << ntext << " texts." << endl; 
} 

} 
int main() 
{ 
    PhoneNumber phone, phone2; // create object phone 
    char answer; 
    int callCounter = 0; 
    int textCounter = 0; 

    cout << "Enter phone number in the form (NNN) NNN-NNNN:\n"; 

    cin >> phone; 

    cout << "Enter phone number in the form (NNN) NNN-NNNN:\n"; 

    cin >> phone2; 

    cout << "The phone number entered was: "; 

    cout << phone << endl; 
    cout << phone2 << endl; 

do { 
cout << "Enter c to make a a call, t to text, s for summary information, or x to exit. " << endl; 
    cin >> answer; 


     if (answer == 'c'){ 
      phone.dialNum(); 
      ++callCounter; 

     } 

     else if (answer == 't'){ 

      cout << "who cares" << endl; 
      ++textCounter; 
     } 

     else if (answer == 's'){ 
      phone.displaySummary(callCounter, textCounter); 
     } 

} while (answer != 'x'); 

    cout << "You made " << callCounter << " calls and " << textCounter << " texts." << endl; 

    return 0; 
} // end main 

Когда я попытался передать объект эти ошибки я получил:

In copy constructor 'PhoneNumber::PhoneNumber(const PhoneNumber&)': 
32:30: error: invalid use of 'PhoneNumber::PhoneNumber' 
In function 'int main()': 
67:16: error: no matching function for call to 'PhoneNumber::PhoneNumber()' 
67:16: note: candidate is: 
30:1: note: PhoneNumber::PhoneNumber(const PhoneNumber&) 
30:1: note: candidate expects 1 argument, 0 provided 
67:23: error: no matching function for call to 'PhoneNumber::PhoneNumber()' 
67:23: note: candidate is: 
30:1: note: PhoneNumber::PhoneNumber(const PhoneNumber&) 
30:1: note: candidate expects 1 argument, 0 provided 
+1

'phonenumberval = phone1. PhoneNumber; '- что вы пытаетесь сделать? – LogicStuff

ответ

3

Выпуск 1: определяемый пользователем оператор приведения

Вы определяете оператора литья с этим кодом:

operator int() const {return phonenumberval;} 

... который я думаю, вы пытаетесь вызвать с этим кодом:

phonenumberval = phone1. PhoneNumber; 

... но это не так, как это работает. Для вызова оператора произнесения, вы должны сделать следующее:

phonenumberval = (int)phone1; 

Выпуск 2: заданного пользователем конструктора

В C++, как только вы предоставляете определенный пользователем конструктор (который вы делаете там, объявляя конструктор копирования PhoneNumber(const PhoneNumber &);), вы теряете конструкторы по умолчанию, предоставляемые языком. В вашем случае вы теряете конструктор по умолчанию PhoneNumber();, что означает, что вы не можете создать новый PhoneNumber без указания параметра конструктору.

Просто добавьте новый конструктор класса PhoneNumber, и все должно быть в порядке.

class PhoneNumber { 
public: 
    PhoneNumber(); // This is the default constructor 
    PhoneNumber(const PhoneNumber &); // This is your copy constructor 

// ... 
}; 

// ... 

int main() 
{ 
    PhoneNumber phone, phone2; // This will call the default constructor, which has to be declared first 
    // ... 
} 
+0

Я бы отказался от использования 'opererator int()', я не вижу, как он подходит для этой проблемы. Лучше просто использовать 'int getPhoneNumberVal() const {return phonenumberval;}' вместо этого. –

+1

@AaronMcDaid: Я согласен. На самом деле, я даже не убежден в использовании 'int' в качестве хранилища для [префиксного кода] (https://en.wikipedia.org/wiki/Prefix_code), например, номера телефонов, поскольку ведущие нули * do * имеют особое значение. – Arkanosis

+0

Теперь, когда я пытаюсь запустить программу, он говорит: /tmp/ccLcOnZQ.o: В функции 'main ': :(. Text.startup + 0x13): неопределенная ссылка на' PhoneNumber :: PhoneNumber()' :(.text.startup + 0x1d): неопределенная ссылка на 'PhoneNumber :: PhoneNumber() ' collect2: ошибка: ld возвращен 1 статус выхода – cookiecrumbler

Смежные вопросы