【发布时间】: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")(您可以删除setYearModel和setMake方法调用)。 -
另外,在标题中包含
using语句是一种不好的做法,但这是另一回事。 -
@zneak:我认为“遗憾的设计选择”指的是最令人烦恼的解析......但这一点也不含糊。在任何情况下,这都不是合法的构造函数调用。
-
@Ben Voigt,我发现在块中允许函数声明毫无意义。我认为
Car honda(int yearModel, string make)行根本不应该编译。 -
@zneak:
using-函数声明呢?你所希望的实际上是一大堆特殊情况。
标签: c++ class constructor