c++ - 新手程序员提出的基本 C++ 问题

标签 c++

我是一名新手 C++ 程序员,正在尝试在学校实验室工作。下面,我粘贴了我正在开发的一个程序的外壳。在 main 中,我实例化属于 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。您正在尝试call声明一个返回类型为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.

关于c++ - 新手程序员提出的基本 C++ 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5957208/

相关文章:

c++ - 需要帮助理解 C++ 中的运算符重载

c++ - 从函数的可变参数构建特定的元组

c++ - 在 C++ 中对扫描的 undefined reference ?

c++ - 如何在指定位置安装Qt?

c++ - 谁为 Qt 开发语言绑定(bind)?

c++ - glGetError() 总是在成功获取上下文后返回 GL_INVALID_OPERATION

c++ - 斐波那契数列 : Elements do not make sense when array size > 28

c++ - 如何使 QTableWidget 中的单元格小部件的背景不可选?

c++ - 为什么在 iOS 中结构对齐不同

c++ - 在 C 中填充二维动态分配数组