【问题标题】:C++ error C2228C++ 错误 C2228
【发布时间】:2013-09-01 04:19:56
【问题描述】:

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

汽车.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;
}

汽车.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' 左侧必须有类/结构/联合

错误 C2228:'.setMake' 左侧必须有类/结构/联合

【问题讨论】:

  • Car honda(int yearModel, string make) 被 C++ 编译器视为函数声明,因为设计选择令人遗憾。改用Car honda(2005, "Accord")(您可以删除setYearModelsetMake 方法调用)。
  • 另外,在标题中包含using 语句是一种不好的做法,但这是另一回事。
  • @zneak:我认为“遗憾的设计选择”指的是最令人烦恼的解析......但这一点也不含糊。在任何情况下,这都不是合法的构造函数调用。
  • @Ben Voigt,我发现在块中允许函数声明毫无意义。我认为Car honda(int yearModel, string make) 行根本不应该编译。
  • @zneak:using-函数声明呢?你所希望的实际上是一大堆特殊情况。

标签: c++ class constructor


【解决方案1】:

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

Car honda(2005, "Accord");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多