C ++错误C2228

时间:2013-09-01 04:19:56

标签: c++ class constructor

我承认我不确定我在这里做什么,所以我正在做很多从我的教科书中复制示例代码并用我自己的程序替换信息...但是可以告诉我什么是造成这个错误?

Car.cpp

// Implementation file for the Car class
#include "Car.h"

// This constructor accepts arguments for the car's year 
// and make. The speed member variable is assigned 0.
Car::Car(int carYearModel, string carMake)
{
    yearModel = carYearModel;
    make = carMake;
    speed = 0;
}

// Mutator function for the car year
void Car::setYearModel(int carYearModel)
{
        carYearModel = yearModel;
}

// Mutator function for the car make
void Car::setMake(string carMake)
{
    carMake = make;
}

Car.h

// Specification file for the Car class
#ifndef CAR_H
#define CAR_H
#include <string>
using namespace std;

class Car
{
private:
    int yearModel; // Car year model
    string make;   // Car make
    int speed;     // Car speed

public:
    Car(int, string); // Constructor

    // Mutators
    void setYearModel(int);
    void setMake(string);

};

#endif 

的main.cpp

#include <iostream>
#include <iomanip>
#include <string>
#include "Car.h"
using namespace std;

int main()
{
    // Create car object
    Car honda(int yearModel, string make);

    // Use mutator functions to update honda object

    honda.setYearModel(2005);
    honda.setMake("Accord");


    return 0;
}

这些是我得到的错误:

错误C2228:'。setYearModel'左边必须有class / struct / union

错误C2228:'。setMake'的左边必须有class / struct / union

1 个答案:

答案 0 :(得分:1)

当你说Car honda(int yearModel, string make);时,你宣布一个名为honda的函数,它接受一个int和一个字符串并返回一个Car。要创建名为honda的Car变量,需要使用实际值调用构造函数:

Car honda(2005, "Accord");