C ++设置多个类成员

时间:2016-08-12 22:40:50

标签: c++ object member

是否可以在一个语句中设置多个不同的类成员?只是一个如何做到这一点的例子:

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

void main()
{
    Animal anml;

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

3 个答案:

答案 0 :(得分:2)

要将Barry的评论“转换”为答案,是的,在the conditions here下:

  

聚合是一个没有用户声明的数组或类(第9节)   构造函数(12.1),没有私有或受保护的非静态数据成员   (第11条),没有基类(第10条),也没有虚函数   (10.3)。

示例:

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

int main() {
    Animal anml;

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

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

答案 1 :(得分:1)

您总是可以重载构造函数或创建在一个语句中设置多个不同对象属性的方法":

#Want to get the total of a single user mensal cost
def total
  user_id.each do |mensal_cost|
  mensal_cost.inject(&:+)
end

#Now the custom validation itself

validate :check_mtotal

  def check_mtotal
    if user_id && total > 1000
    errors.add(:user_id, message: 'cant add more animals')
  end
end

答案 2 :(得分: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;
}

任何有xyhttps://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;
}
相关问题