如何使用带参数的对象作为类成员
leon 2008-02-25 05:10:03 看如下示例:
class CStudent
{
int m_age;
CStudent(int age = 16)
{
m_age = age;
}
}
class CClass
{
CClass()
{
}
private:
CStudent m_student1;
CStudent m_student2(10); // 本意定义一个age为10的对象
// 错误error C2059: syntax error:’constant’
}
如上例,要想在类CClass中使用一个带参数的对象m_student2,以上的定义方式是错误的。
语法上说,编译器把这个CStudent m_student2(10);当成了函数声明,报告错误:error C2059: syntax error:’constant’
从类定义的角度来看,定义成员变量时并不会实例化该变量,没有内存分配,但是CStudent m_student2(10);这种写法也意味着实例化一个对象,所以是不允许的。那么,这也意味着直接声明一个带参数的成员变量是不可能的,不知道这种理解对不对?
希望有高手指点~~