新手程序员的基本C++问题

Basic C++ question from a novice programmer

本文关键字:C++ 问题 程序员 新手      更新时间:2023-10-16

我是一名新手C++程序员,正在尝试在学校实验室工作。下面,我粘贴了我正在处理的程序的外壳。总的来说,我正在实例化属于class Velocity的对象car1。当我尝试将此实例化与函数 mpsConverter 一起使用时,我收到一个错误,指示表达式必须具有类类型。我们在课堂上做过类似的例子,这种格式工作得很好。有什么想法吗?如果这不是处理此类简单问题的合适论坛,请指出我正确的方向,以找到更合适的论坛。

谢谢,艾尔

// P1_2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include "conio.h"
using namespace std;
class Velocity
{
    private:
        int mpsInput;       // input value: meters per second (mps)
        int kmphInput;      // input value: km per hour
        int mphOutput;      // output value: comverted value of km per hour to miles per hour (mph) 
    public:
        int kmphOutput;     // output value: converted value of mps to km per hour
        Velocity();             
        void mpsConverter(int speedKmph);
        void mphConverter();
        ~Velocity();
};
Velocity::Velocity()        // Constructor
{
    cout << "The initial is text is displayed when an object in the class Velocity is Instantiated." << endl;
}
void Velocity::mpsConverter(int speedKmph)      // convert KM per hour into meters per second (mps)
{
    kmphOutput = (speedKmph * 2); 
}
void Velocity::mphConverter()       // convert KM per hour into miles per hour (mph)
{
}
Velocity::~Velocity()       // Destructor
{
}
int main()
{
    Velocity car1();
    car1.mpsConverter(2);
    getch();
    return 0;
}
Velocity car1();

上述语句不是创建类型为 Velocity 的实例car1。您正在尝试调用声明一个返回类型为 Velocity 的函数car1()。由于没有创建实例 -

car1.mpsConverter(2); // This statement is giving you error stating mpsConverter(2)
                      // can only be called on class types.
Velocity car1 ; // This is the right way of instance creation.