定义一个包含3个int值的类型

use*_*183 -4 c++ variables

我是C++的新手,无法弄清楚如何定义一个包含3个值的变量,例如坐标保持2个值,如(x,y).

我试过了:

typedef int U_K(int a,int b,int c);
Run Code Online (Sandbox Code Playgroud)

但这似乎不起作用.

我真的很感激快速回答:)

谢谢!

编辑:所以我做了这个:

struct U_K{
    float a,b,c;
};
    U_K Uk; //this line
Run Code Online (Sandbox Code Playgroud)

这是错的吗?因为我获得了该行的"未知类型名称U_K"...我首先是因为我需要在我将要使用结构的函数下声明它,但结果是两种情况都有错误.

Rax*_*van 5

最短的方法是使用a struct

struct U_K
{
    int a,b,c;
};
Run Code Online (Sandbox Code Playgroud)

用法:

U_K tmp;
tmp.a = 0;
tmp.b = 1;
tmp.c = 2;
Run Code Online (Sandbox Code Playgroud)

您可以通过添加成员函数/构造函数来增加该类型的复杂性,以便U_K更轻松地使用:

struct U_K
{
    int a,b,c;
    U_K() //default constructor
        :a(0)
        ,b(0)
        ,c(0)
    {}
    U_K(int _a_value,int _b_value, int _c_value) //constructor with custom values
        :a(_a_value)
        ,b(_b_value)
        ,c(_c_value)
    {}

};
//usage:
int main()
{
    U_K tmp(0,1,2);
    std::cout << "a = " << tmp.a << std::endl;//print a
    std::cout << "b = " << tmp.b << std::endl;//print b
    std::cout << "c = " << tmp.c << std::endl;//print c
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用std :: tuple来获得相同的结果.使用它是不同的:

std::tuple<int,int,int> t = std::make_tuple(0,1,2);
std::cout << "a = " << std::get<0>(t) << std::endl;//print first member
std::cout << "b = " << std::get<1>(t) << std::endl;//print second member
std::cout << "c = " << std::get<2>(t) << std::endl;//print third member
Run Code Online (Sandbox Code Playgroud)

如果你现在正在学习c ++,你应该知道实现std::tuple比一个简单的结构要复杂得多,要理解它你需要学习模板和可变参数模板.

  • 我甚至建议使用`std :: tuple`,我不认为使用新手特别困难.`typedef std :: tuple <int,int,int> U_K;`. (3认同)