马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
问题1,如下代码#include <iostream>
using namespace std;
class A{
public:
A(){cout<<'x';}
};
class B:public A{
private:
int x;
public:
B(int x):A(),x(x){cout<<x<<'t';}
};
class C{
private:
A a;
B b;
public:
C(int x):b(x){cout<<'r';}
};
void f(){
A a1;
B b1(2);
C c1(3);
}
int main() {
cout<<"bienvenue!\n";
f();
cout<<"au revoire!\n";
}
输出为:bienvenue!
xx2txx3trau revoire!
Process finished with exit code 0
我想问对象a1输出x 对象b1输出x2t,对象c1输出xx3tr,我就想问开始的两个“xx”是从哪来的,为啥我自己写的只有一个x呢?
问题2:如下代码#include <iostream>
using namespace std;
class A{
public:
A(){cout<<'a';}
~A(){cout<<"b\n";}
};
class B:public A{
private:
int x;
public:
B(int x):A(),x(x){cout<<'c'<<x;}
~B(){cout<<"~B"<<x;}
};
class C{
private:
A a;
B b;
public:
C(int x):b(x){cout<<'d';}
~C(){cout<<'e';}
};
void f(){
A a1;
B b1(2);
C c1(3);
}
int main() {
cout<<"hello\n";
f();
cout<<"goodbye\n";
}
输出结果为:hello
aac2aac3de~B3b
b
~B2b
b
goodbye
Process finished with exit code 0
我想问我开始写出来的和输出结果完全不一样,请问有大神可以细致讲解下这个每一步的构造和析构过程吗,谢谢~!
问题3:如下代码#include <iostream>
using namespace std;
class A{
public:
void f(){cout<<"hello!";}
};
int max(int *p,int n){
int max=p[0];
for(int i=1;i<n;i++){
if(max<p[i]){
max=p[i];
}
return max;
}
void fillMax(int *p,int n){
int max=max(*p,n);
for(int i=0;i<n;i++){
*p++=max;
}
}
}
int main() {
A a1;
A a2();
A *p;
const A a3;
p=&a1;
//p=&a3; illegal, a3 is const;
const A *q;
q=&a1;
//A *const r; r can not change, must be initialized??????????????
a1.f();
p->f();//(*p).f()
(*p).f();
//a2.f(); illegal
//q->f(); illegal q is a pointer to const, f is not const;
return 0;
}
我想问一下A *const r; const A r; A const *r; const A *r; A const r 有啥区别呢,在实现p->f()的时候分别有哪些结果呢?
A *const r; r can not change, must be initialized??????????????这一句为啥要初始化,const A * q; A const *q就不用初始化呢?
#include <iostream>
class A
{
public:
int x;
A(): x(0) {}
void f()
{
std::cout << "hello!" << std::endl;
}
};
int main()
{
A a1;
A a2;
A *const r = &a1; // 变量r是一个指针,这个const用来限制变量r,r只能在初始化的时候指向一个对象,之后就一直指向这个对象并且不能再指向其他对象
r->x = 100; // 可以
r->f(); // 可以
//r = &a2; // 不可以
return 0;
}
|