2016-04-07 15 views
-3

Was ist falsch an diesem Code, um diesen Fehler weiterhin zu erhalten?cout/cin nennt keinen Typfehler

Der Fehler trat nur auf, wenn statt "distanceFormula" in main, ich habe es zu seiner eigenen Klasse.

#include <iostream> 
#include <string> 

using namespace std; 

class distanceFormula { 
    public: 
int speed; 
int time; 
int distance; 

cout << "What is the speed?" << endl; 
cin >> speed; 

cout << "How long did the action last?" << endl; 
cin >> time; 


distance = speed * time; 

cout << "The distance traveled was " << distance << endl; 
}; 




int main() 
{ 
distanceFormula ao 
ao.distanceFormula; 

return 0; 
}; 
+0

Warum haben Sie eine eigene Klasse? Hast du deinen Code überhaupt kompiliert ?? –

+1

Unterscheiden Sie Funktion und Klasse. –

+1

'ao.distanceFormula;' Was soll das tun? – drescherjm

Antwort

0

Der Körper der Klassendeklaration kann nur Glieder enthalten können, die entwederDaten oder Funktion Deklarationen und optional Zugang Spezifizierer sein kann.

Wickeln Sie Ihren Code in einer Funktion und dann die von einem Objekt in main nennt

class distanceFormula { 
public: 
int speed; 
int time; 
int distance; 
void init() 
{ 
    cout << "What is the speed?" << endl; 
    cin >> speed; 

    cout << "How long did the action last?" << endl; 
    cin >> time; 
    distance = speed * time; 
    cout << "The distance traveled was " << distance << endl; 
} 
}; 

int main() 
{ 
    distanceFormula ao; 
    ao.init(); 
    return 0; 
}; 
+0

Danke! das einzige nicht-kritisierende XD –

+0

@AmmarT. Ich aktualisierte die Antwort, fügte den Grund auch hinzu! –

0

Wenn Sie immer noch eine Klasse verwenden. Hier ist, wie Sie es tun:

#include <iostream> 

class distanceFormula 
{ 
private: 
    int speed; // private 
    int time; // private 
public: 
    distanceFormula(); // constructor 
    int getSpeed(); // to get 
    int getTime(); // to get 
    int getDistance(); // to get 
    void setSpeed(int); // to set 
    void setTime(int); // to set 
}; 

distanceFormula::distanceFormula() 
{ 
    this->time = 0; 
    this->speed = 0; 
} 

int distanceFormula::getSpeed() 
{ 
    return this->speed; 
} 
int distanceFormula::getTime() 
{ 
    return this->time; 
} 
int distanceFormula::getDistance() 
{ 
    return this->time * this->speed; 
} 
void distanceFormula::setSpeed(int speedVal) 
{ 
    this->speed = speedVal; 
} 
void distanceFormula::setTime(int timeVal) 
{ 
    this->time = timeVal; 
} 


int main() 
{ 
    distanceFormula YourObject; // create obj 
    int SpeedValue; 
    int TimeValue; 
    std::cout << "Enter the Speed:"; 
    std::cin >> SpeedValue; // take speed 

    std::cout << "Enter the Time:"; 
    std::cin >> TimeValue; // take time 


    YourObject.setSpeed(SpeedValue); // set 
    YourObject.setTime(TimeValue); // set 

    std::cout << "This is the distance: " << YourObject.getDistance(); // retrieve result 

    getchar(); // wait 
    return 0; 
}