修改一
#include <iostream>
using namespace std;
class C
{
private:
int x;
public:
C(int a);
int getX()const{return x;}
};
C::C(int a):x(a){}
void main()
{
const C c(5);
cout<<c.getX();
system("pause");
} 修改二
#include <iostream>
using namespace std;
class C
{
private:
int x;
public:
C(int x){this->xx = x;}
int getX(){return x;}
};
void main()
{
C c(5);
cout<<c.getX();
system("pause");
} 倾向于第二种吧,刚开始还不怎么熟悉这种博文发布形式,多试几次就会熟练使用这种发博文了
本文通过两个示例展示了C++中类的构造函数及其成员变量初始化的不同方式。第一种方式采用初始化列表进行成员变量的正确初始化,第二种方式则直接在构造函数体内赋值。文章强调了初始化列表的重要性,并提供了代码示例。
1788

被折叠的 条评论
为什么被折叠?



