我想在接口类和派生类中使用浮点值(defaultColor)作为默认参数。那么我应该如何定义浮点默认颜色[].?
//Interface class
static float defaultColour[]={0,0,0,0}; //This become error
class Interface{
virtual void print_color(float *color = defaultColour)=0;
}
//Use Interface Derived.h
class Derived : public Interface{
void print_color(float *a = defaultColour);
}
//Derived.cpp
void Derived :: print_color(float *a){
//some code using color a[]
}
默认数组值实际上应该不是问题。 整理好示例中的语法错误后,以下示例对我来说效果很好:
#include <iostream>
#include <memory>
static float default_array[] = { 42.0f, 13.0f, 2.0f, 0.0f };
struct Interface
{
virtual void foo(float *a = default_array) = 0;
};
struct Derived : public Interface
{
void foo(float *a);
};
// Silly contrived example: output array values until a 0 is hit. You
// better make sure there actually is a 0 at the end.
void Derived::foo(float *a)
{
while (*a != 0.0f)
{
std::cout << *a << std::endl;
++a;
}
}
int main()
{
std::unique_ptr<Interface> i(new Derived);
std::cout << "i->foo():" << std::endl;
i->foo();
float other_array[] = { 1.0f, -2.0f, 3.0f, -4.0f, 0.0f };
std::cout << "i->foo(other_array):" << std::endl;
i->foo(other_array);
}
但请注意,如果多个编译单元包含一个定义规则,则在标头中定义default_array
将违反该规则。 为了避免这种情况,您必须使用 @MartinBonner 的解决方案并使数组成为静态成员变量。
如果你知道你只能通过指向Interface
的指针来调用foo()
,那么你不需要在Derived::foo
的声明中重新指定默认值。 但是,如果您还希望执行以下操作:
Derived der;
der.foo();
然后你会遇到一个问题,因为它实际上并不存在Derived::foo()
。 海湾合作委员会将投诉:
test.cpp: In function ‘int main()’:
test.cpp:37:15: error: no matching function for call to ‘Derived::foo()’
der.foo();
^
test.cpp:37:15: note: candidate is:
test.cpp:18:10: note: virtual void Derived::foo(float*)
void Derived::foo(float *a)
^
test.cpp:18:10: note: candidate expects 1 argument, 0 provided
在这种情况下,一个有点通用的解决方法可能是将以下内联函数声明添加到Derived
:
inline void foo() { static_cast<Interface*>(this)->foo(); }
使defaultColour
成为 Interface 的常量静态公共成员。
接口.h
class Interface{
public:
static float defaultColour[colourSize]; // You have got a const for the
// array size somewhere,
// haven't you?
virtual void print_color(float *color = defaultColour)=0;
}; // Need trailing ; here
派生.h
class Derived : public Interface { // Need to derive from Interface.
public:
void print_color(float *a = defaultColour); // Just declare function here.
};
派生.cpp
void Derived::print_color(float *a){ // define function here.
//some code using color a[]
}
界面.cpp(这可能是一个新文件)
float Interface::defaultColour[] = {255,255,255,150};
好的。谢谢大家。我用这种方式解决了。有什么不好的规定吗?
//Interface class
class Interface{
public:
virtual void print_color(const float *color = defaultColour)=0;
protected:
static const float defaultColour[4];
}
//Use Interface Derived.h
class Derived : public Interface{
void print_color(const float *a = defaultColour);
}
//Derived.cpp
Interface::defaultColour[]={0,0,0,0};
void Derived :: print_color(const float *a){
//some code using color a[]
}