简体   繁体   English

C ++将“默认”结构传递给函数

[英]C++ passing “default” struct to function

I'm trying to figure out how I can "pass default struct values" to a function without initializing the struct, this is what I have now: 我试图弄清楚如何在不初始化结构的情况下将“默认结构值”传递给函数,这就是我现在所拥有的:

struct Color3i
{
    Color3i(): r(255), g(255), b(255) { }
    int r, g, b;
};

void CCore::Color(Color3i color)
{
    double red, green, blue;
    red = color.r / 255.0f;
    green = color.g / 255.0f;
    blue = color.b / 255.0f;

    glColor3f(red,green,blue);
}

Color3i defaultColor;
Core.Color(defaultColor);

What I'm trying to do would look like this but this clearly doesn't work: 我想做的事情看起来像这样,但这显然行不通:

Core.Color(Color3i defaultColor);

How would I pass the struct to the function without initializing it with Color3i defaultColor; 我如何将结构传递给函数而不用Color3i defaultColor初始化它; is this possible? 这可能吗?

Sorry if this has been asked before but I tried searching the interwebs but I couldn't find anything (maybe I'm using the wrong keywords to search) 抱歉,以前是否有人问过这个问题,但是我尝试搜索网络,但找不到任何内容(也许我使用了错误的关键字进行搜索)

You should just be able to do this: 您应该能够执行以下操作:

Core.Color(Color3i());

That is, call the default constructor to initialize a new instance, and pass it. 也就是说,调用默认的构造函数来初始化一个新实例并传递它。

There are a few ways to pass an information that you want the color to be default. 有几种方法可以传递您希望颜色为默认值的信息。 The simplest one is given in the comments already: 最简单的一个已经在注释中给出:

Core.Color(Color3i())

If you want the code to be shorter, you can set the default value in the function parameter you invoke: 如果要缩短代码长度,可以在调用的函数参数中设置默认值:

void CCore::Color(Color3i color = Color3i()) { ... }

....
Core.Color(); //no argument = default

If you want to be more descriptive instead, you can create a static function acting as a constructor in the Color : 如果您想更具描述性,可以在Color创建一个静态函数充当构造函数:

struct Color3i {
    Color3i(): r(255), g(255), b(255) { }
    int r, g, b;
    static Colo3i defaultColor() { return Color3i(); }
};
...
Core.Color(Color3i::defaultColor());

Finally, if you want to control the context where the default color can be used, you can create a new dummy enum type and overload the function(s) to accept the default version explicitly: 最后,如果要控制可以使用默认颜色的上下文,则可以创建一个新的虚拟枚举类型并重载该函数以显式接受默认版本:

enum DefaultColorEnum {
    DefaultColor
};

void CCore::Color(Color3i color) {
    ... //normal code
}

void CCore::Color(DefaultColorEnum) { //ignore the parameter value, the type is what matters
    Color(Color3i()); //invoke the generic version with default value
}

...

Core.Color(DefaultColor);

It all depends on what you actually wants to achieve... 这完全取决于您实际想要实现的目标...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM