很久没用过结构体了,稍微复习一下。
第一种,通过冒号初始化
结构体名(传入参数): 成员变量1(参数1),成员变量2(参数2){};
struct Entry{
Keytype _key;
Valuetype _value;
Entry(Keytype key=NULLKEY,Valuetype value=0): _key(key),_value(value){}
};
int main(){
Entry a;
Entry b(2,3);
cout<< a._key << a._value <<endl;
cout<< b._key << b._value <<endl;
return 0;
}
第二种,{}初始化
Entry c={2,3};
cout<< c._key << c._value <<endl;
注意,如果是列表初始化的,那么仍然可以用{}进行初始化
第三种,构造函数初始化
#include <iostream>
using namespace std;
typedef int Keytype;
typedef int Valuetype;
#define NULLKEY -1
struct Entry{
Keytype _key;
Valuetype _value;
// Entry(Keytype key=NULLKEY,Valuetype value=0): _key(key),_value(value){}
Entry(Keytype key,Valuetype value){
this->_key = key;
this->_value = value;
}
};
int main(){
// Entry a;
Entry b(2,3);
Entry c={2,3};
// cout<< a._key << a._value <<endl;
cout<< b._key << b._value <<endl;
cout<< c._key << c._value <<endl;
return 0;
}
实际测试并不存在以下情况
注意: struct如果定义了构造函数的话,就不能用大括号进行初始化了,即不能再使用指定初始化与顺序初始化了。