1.C++类没有对其成员显示声明访问权限时,是不是默认为私有?
回答:
对于类:如果没有指定访问修饰符,默认情况下第一个成员之前的访问级别是private。这意味着如果你没有为类的第一个成员明确指定访问级别,它将被视为private,并且这个默认访问级别会应用到所有后续成员,直到遇到另一个访问修饰符为止。
对于结构体:与类不同的是,结构体在C++中的默认访问级别是public。也就是说,如果你在一个结构体内定义成员而没有指定访问修饰符,这些成员将默认为public。
2.静态对象的范围是贯穿程序的生命周期。
#include<iostream>
using namespace std;
class Apple
{
int i;
public:
Apple()
{
i = 0;
cout << "Inside Constructor\n";
}
~Apple()
{
cout << "Inside Destructor\n";
}
};
int main()
{
int x = 0;
if (x==0)
{
static Apple obj;
}
cout << "End of main\n";
}
输出:
Inside Constructor
End of main
Inside Destructor
即在main结束后调用析构函数
3.静态成员函数仅访问静态数据成员或其他静态成员函数,它们无法访问类的非静态数据成员或成员函数。
4.在C++中,不能在类定义内部对静态成员变量进行初始化(除非是 const static 整型常量 或 C++11 起支持的 constexpr)
正确的做法是:
在类内 声明 静态成员变量;
在类外 定义并初始化 它。
#include <iostream>
using namespace std;
class Apple
{
public:
static int i; // 声明静态成员变量,不能在这里初始化
// 静态成员函数
static void printMsg()
{
cout << "Welcome to Apple!" << endl;
cout << "i = " << i << endl;
}
};
// 在类外定义并初始化静态成员
int Apple::i = 123;
// main 函数
int main()
{
Apple app;
app.printMsg(); // 可以通过对象调用(也可以用 Apple::printMsg())
return 0;
}
或者
#include<iostream>
using namespace std;
class Apple
{
public:
static const int i = 123;
// static member function
static void printMsg()
{
cout<<"Welcome to Apple!"<<endl;
cout<<"i="<<i<<endl;
}
};
// main function
int main()
{
// invoking a static member function
Apple::printMsg();
Apple app;
app.printMsg();
cout<<"i="<<app.i;
}
运行结果:
Welcome to Apple!
i=123
Welcome to Apple!
i=123
i=123
6573

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



