我有以下文件:
车
#include <iostream>
using namespace std;
namespace CarLibrary {
class Car {
private:
string& _producer;
string& _model;
string& _color;
public:
Car(const string& producer,
const string& model,
const string& color);
string Show();
};
car.cpp
#include "car.h"
namespace CarLibrary {
Car::Car(const string& producer,
const string& model,
const string& color)
{
_producer = producer;
_model = model;
_color = color;
}
string Car::Show()
{
return _model + " (" + _producer + "): color " + _color ;
}
}
我收到这些错误:
C:... \ car.cpp:5:错误:'CarLibrary :: Car'的构造函数必须显式初始化引用成员'_producer'
C:.. \ car.cpp:5:错误:'CarLibrary :: Car'的构造函数必须显式初始化引用成员'_model'
C:... \ car.cpp:5:错误:'CarLibrary :: Car'的构造函数必须显式初始化引用成员'_color'
我正在观看视频讲座,重复教授的工作,但奇怪的是,即使我只是复制完全相同的代码,教授也没有出现任何错误。知道有什么问题吗?
必须将引用初始化为引用某些内容。
在创建引用之后,您可以在此处尝试分配这些引用。那是不合法的:
Car::Car(const string& producer,
const string& model,
const string& color)
{
_producer = producer;
_model = model;
_color = color;
}
解决方案是使用成员初始化器列表:
Car::Car(const string& producer,
const string& model,
const string& color) : // colon indicates the start of the member init list
_producer(producer),
_model(model),
_color(color)
{
// constructor body - now empty
}
注意:要使此方法起作用,您的成员引用变量也必须为const
。参考成员通常不是您想要的。我建议将它们设置为正常值std::string
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句