如何在 C++ 中的一条语句中设置多个 class 成员?

How do I set multiple class members in one statement in C++?

是否可以在一条语句中设置多个不同的 class 成员?这只是如何完成的一个例子:

class Animal
{
    public:
        int x;
        int y;
        int z;
};

void main()
{
    Animal anml;

    anml = { x = 5, y = 10, z = 15 };
}

把"convert"巴里的评论改成一个答案,对,在the conditions here下:

An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).

示例:

class Animal
{
    public:
        int x;
        int y;
        int z;
};

int main() {
    Animal anml;

    anml = { 5, 10, 15 };
    return 0;
}

(此 Community Wiki 答案是根据 this meta post 添加的。)

您始终可以重载构造函数或创建 "set multiple different object properties in one statement":

的方法
class Animal {
public:
  Animal() {

  };

  Animal(int a, int b, int c) {
    x = a;
    y = b;
    z = c;
  }

  void setMembers(int a, int b, int c) {
    x = a;
    y = b;
    z = c;
  }

private:
  int x;
  int y;
  int z;
};

int main() {
  // set x, y, z in one statement
  Animal a(1, 2, 3);

  // set x, y, z in one statement
  a.setMembers(4, 5, 6);

  return 0;
}

动物的解决方案 1 (http://ideone.com/N3RXXx)

#include <iostream>

class Animal
{
    public:
        int x;
        int y;
        int z;
        Animal & setx(int v) { x = v; return *this;}
        Animal & sety(int v) { y = v; return *this;}
        Animal & setz(int v) { z = v; return *this;}
};

int main() {
    Animal anml;
    anml.setx(5).sety(6).setz(7);
    std::cout << anml.x << ", " << anml.y << ", " << anml.z << std::endl;
    return 0;
}

任何 class 与 xy (https://ideone.com/xIYqZY)

的解决方案 2
#include <iostream>

class Animal
{
    public:
        int x;
        int y;
        int z;
};


template<class T, class R> T& setx(T & obj, R x) {  obj.x = x;  return obj;}
template<class T, class R> T& sety(T & obj, R y) {  obj.y = y;  return obj;}

int main() {
    Animal anml;
    sety(setx(anml, 5), 6);
    std::cout << anml.x << ", " << anml.y << std::endl;
    return 0;
}