gpt4 book ai didi

c++ - 不能将初始化列表与继承结合起来

转载 作者:行者123 更新时间:2023-11-28 01:17:40 24 4
gpt4 key购买 nike

我有一些代码,我希望类实例能够在其初始化程序中初始化变量,同时还在其初始化程序列表中调用父类构造函数。这个父类构造函数将在它自己的构造函数的初始化列表中初始化三个额外的变量。

这里是一些在不同类上使用这些构造函数的代码:

class Vec3f {
public:
inline Vec3f () : x (0), y (0), z (0) {}
inline Vec3f (float xx, float yy, float zz) : x (xx), y (yy), z (zz) { }
private:
float x,y,z;
};

class Vec4f : Vec3f {
public:
inline Vec4f (): Vec3f(), w(0) {}
inline Vec4f (float a,float b,float c,float d): Vec3f (a,b,c), w(d) {}
private:
float w;
};

class Matrix4x4 {
public:
void setIdentity ();
private:
Vec4f row1, row2, row3, row4;
};

void Matrix4x4::setIdentity () {
row1 (1.0f,0.0f,0.0f,0.0f);
row2 (0.0f,1.0f,0.0f,0.0f);
row3 (0.0f,0.0f,1.0f,0.0f);
row4 (0.0f,0.0f,0.0f,1.0f);
}


main () {
Matrix4x4 a;
a.setIdentity ();
}

当我运行上面的代码时,我收到:

test.cpp: In member function ‘void    Matrix4x4::setIdentity()’:
test.cpp:26: error: no match for call to ‘(Vec4f) (float, float, float, float)’
test.cpp:27: error: no match for call to ‘(Vec4f) (float, float, float, float)’
test.cpp:28: error: no match for call to ‘(Vec4f) (float, float, float, float)’
test.cpp:29: error: no match for call to ‘(Vec4f) (float, float, float, float)’

在另一个留言板上有人建议:

class Vec3f {
public:
inline Vec3f () : x (0), y (0), z (0) {}
inline Vec3f (float xx, float yy, float zz) : x (xx), y (yy), z (zz) { }
inline void Set3f (float xx, float yy, float zz) {
x = (xx);
y = (yy);
z = (zz);
}
private:
float x,y,z;
};

class Vec4f : Vec3f
{
public:
inline Vec4f (): Vec3f(), w(0) {}
inline Vec4f (float a,float b,float c,float d): Vec3f (a,b,c), w(d) {}
inline void Set4f (float a,float b,float c,float d) {
Set3f(a,b,c);
w = d;
}
private:
float w;
};

class Matrix4x4 {
public:
void setIdentity ();
Matrix4x4() :
row1 (1.0f,0.0f,0.0f,0.0f),
row2 (0.0f,1.0f,0.0f,0.0f),
row3 (0.0f,0.0f,1.0f,0.0f),
row4 (0.0f,0.0f,0.0f,1.0f)
{}
private:
Vec4f row1, row2, row3, row4;
};

void Matrix4x4::setIdentity () {
row1.Set4f(1.0f,0.0f,0.0f,0.0f);
row2.Set4f(0.0f,1.0f,0.0f,0.0f);
row3.Set4f(0.0f,0.0f,1.0f,0.0f);
row4.Set4f(0.0f,0.0f,0.0f,1.0f);
}


int main () {
Matrix4x4 a;
a.setIdentity ();
}

但是,这对我来说似乎是一个 hack。不想调用两个 setter 方法。最好只在普通构造函数中做我需要的,更少的代码。所以我问:为什么 C++ 不允许构造函数初始化列表按我想要的方式工作?

最佳答案

您没有在 setIdentity() 中使用构造函数的初始化列表,这就是您的代码失败的原因。

Vec4f 没有实现 operator()(function call operator),所以像

这样的语句

row1 (1.0f,0.0f,0.0f,0.0f);

setIdentity() 的内部不起作用,而且它们不会按照您认为的那样进行。

您可能打算构建新的 Vec4f 实例并将它们分配给现有变量,例如:

void Matrix4x4::setIdentity () {
row1 = Vec4f(1.0f,0.0f,0.0f,0.0f);
row2 = Vec4f(0.0f,1.0f,0.0f,0.0f);
row3 = Vec4f(0.0f,0.0f,1.0f,0.0f);
row4 = Vec4f(0.0f,0.0f,0.0f,1.0f);
}

关于c++ - 不能将初始化列表与继承结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58107787/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com