cout / cin没有命名类型错误

时间:2016-04-07 03:23:55

标签: c++

此代码有什么问题继续收到此错误?

错误只发生在而不是放置" distanceFormula"在主要方面,我把它作为自己的班级。

#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;
};

2 个答案:

答案 0 :(得分:0)

类声明的主体只能包含成员,可以是数据功能声明,也可以是访问说明符。< / p>

将代码包装在函数中,然后通过对象在main中调用它

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;
};

答案 1 :(得分:0)

如果你仍然需要使用课程。这是你如何做到的:

#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;
}