2016-08-12 49 views
0

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

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

void main() 
{ 
    Animal anml; 

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

'无效的主要()'在C++非法。在获得票证之前,你会想把它改成'int main()'。 –

+3

您需要查看[汇总](http://stackoverflow.com/q/4178175/2069064)是什么。 – Barry

回答

2

“转换”巴里的评论到一个答案,是的,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; 
} 

(按照加入与this meta post这个社会维基答案)

1

您可以随时超载的构造方法或创建方法在一个声明中说:“设置多个不同的对象属性“:

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; 
} 
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; 
} 

溶液2为任何类xyhttps://ideone.com/xIYqZY

#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; 
}