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

时间:2011-05-10 22:24:21

标签: c++

我是一名新手C ++程序员,正在尝试在学校实验室工作。下面,我已经粘贴了我正在处理的程序的shell。在main中,我实例化了属于car1的对象class Velocity。当我尝试使用函数mpsConverter进行此实例化时,我收到一个错误,指示表达式必须具有类类型。我们在课堂上做了类似的例子,这种格式运行良好。有任何想法吗?如果这不是适合此类简单问题的适当论坛,请指出正确的方向指向更合适的问题。

谢谢,Al

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

1 个答案:

答案 0 :(得分:6)

Velocity car1();

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

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.