cout/cin没有命名类型错误

cout/cin does not name a type error

本文关键字:类型 错误 cin cout      更新时间:2023-10-16

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

只有当我没有把"distance Formula"放在主要内容中,而是把它作为自己的类时,错误才会发生。

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

类声明的主体只能包含成员,这些成员可以是数据函数声明,也可以是访问说明符

将代码封装在一个函数中,然后用对象在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;
};

如果您仍然需要使用一个类。以下是您的操作方法:

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