我有一个带有两个构造函数的 C++ 类(一个默认构造函数和另一个带参数的构造函数)。为了重用代码,我避免在构造函数级别初始化类成员,而是在 Initialize 方法中执行此操作,我从两个构造函数调用该方法。这样,我希望尽量减少代码行和重复代码:
Location::Location(){
double pos[POSITION_SIZE] = {0};
this->Initialize(const_cast<char*>(""), const_cast<char*>(""), pos);
}
Location::Location(char *id, char *code, double pos[POSITION_SIZE]){
this->Initialize(id, code, pos);
}
void Location::Initialize(char *id, char *code, double pos[POSITION_SIZE]){
strcpy(this->ID, id);
strcpy(this->code, code);
this->position[0] = pos[0];
this->position[1] = pos[1];
this->position[2] = pos[2];
this->attribute1 = 0;
this->attribute2 = 0;
}
标题:
class Location{
public:
Location();
Location(char *id, char *code, double pos[POSITION_SIZE]);
private:
// This method initializes the location attributes given as parameters
void Initialize(char *id, char *code, double pos[POSITION_SIZE]);
// Name/identifier of the location
char ID[ID_LENGTH];
// FIR identifier
char code[ID_LENGTH];
// Location's coordinates (lat, lon, alt)
double position[POSITION_SIZE];
// Attribute 1
double attribute1;
// Attribute 2
double attribute2;
};
我知道使用初始化方法是一种不好的做法,因为例如老派编码风格或避免在构造函数中使用异常。但我的目标是减少代码,所以除非 stackoverflow 的一些大师说相反,否则我认为这没有错(但我是来学习的,所以请摧毁我所有的信念)。
问题是我收到警告,提示我没有在构造函数中初始化类成员。编译器不希望它们在 Initialize 方法中被初始化。那么,有什么方法能让编译器开心吗?我应该忘记 aboput Initialize 方法的用法吗?
最佳答案
我会使用构造函数委托(delegate),比如:
#include <iostream>
using namespace std;
class foo
{
public:
foo()
: foo(1, "2", 3.) // delegate to the other constructor with defaults...
{ }
foo(int a, std::string b, double c)
: _a(a), _b(b), _c(c)
{ }
private:
int _a;
std::string _b;
double _c;
};
int main() {
foo f1{};
foo f2{1, "3", 4.};
return 0;
}
请注意,您至少可以使用 c++11...
关于C++ 类成员未初始化(在构造函数中,但在初始化方法中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27959327/