65.9K
CodeProject 正在变化。 阅读更多。
Home

如何为结构参数实现默认值

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.47/5 (34投票s)

2003年12月12日

viewsIcon

142291

如何在结构体参数中实现默认值。

引言

有人问我如何在 struct 中实现默认参数值。他希望能够进行以下调用

MyStruct st = {200,50);

foo();   // No parameters means the default ones
foo(st); // Use the parameters passed

他尝试了以下方法

struct MyStruct 
{ 
    int a; 
    int b;

};
 
void foo(MyStruct st={100,100}) 
{
    cout << st.a << " " << st.b << endl;
}

然而,编译器 (VC 6) 无法编译这段代码。

解决方案

您可以在 struct 中使用构造函数。这并不是很优雅,但它能工作。

struct MyStruct 
{
    MyStruct(int x, int y)
    {
        a = x;
        b = y;
    }
    int a; 
    int b;

};

void foo(MyStruct st=MyStruct(100,100)) 
{
    cout << st.a << " " << st.b << endl; 
}

第二个解决方案,我更喜欢一点

struct MyStruct 
{
    int a; 
    int b;
};
static const MyStruct stDefValue = { 100, 100 };

void foo(MyStruct st=stDefValue) 
{
    cout << st.a << " " << st.b << endl;
}

结论

这没什么大不了的,你可能会觉得它在面向对象编程方面不是很好,但当你想要做类似的事情时,了解它会很有用。

© . All rights reserved.