Error: constructor must explicitly initialize reference member
Error: constructor must explicitly initialize reference member
我有以下文件:
car.h
#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
s.
我有以下文件:
car.h
#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
s.