笔试题东方国

c++基础面试

1、构造析构顺序。

#include<iostream>
#include<vector>
using namespace std;

class A {
public:
	A() {
		cout << "A is created" << endl;
		Print();
	}
	~A() {
		cout << "A is deleted" << endl;
	}
	virtual void Print() {
		cout << "A::Print called" << endl;
	}
};

class B : public A {
public:
	B() {
		cout << "B is created" << endl;
		Print();
	}
	~B() {
		cout << "B is deleted" << endl;
	}
	virtual void Print() {
		cout << "B:: Print called" << endl;
	}
};

int main() {
	A* pA = new B();
	delete pA;
	return 0;
}


# 执行结果:先执行A的构造,和A构造内部的函数,再执行B的构造函数,和B构造内部的函数,
delete pA这个指针,只会执行A的析构函数,怎么改?
把A的析构函数搞成虚函数。
A is created
A::Print called
B is created
B:: Print called
A is deleted

2、

#include<iostream>
#include<vector>
using namespace std;
class A {
private:
	int m_value;
public:
	A(int value) {
		m_value = value;
	}
	void Print1() {
		printf("hello world ,print1");
	}
	virtual void Print2() {
		printf("hello world ,print2");
	}
	void Print3() {
		printf("%d", m_value);
	}

};
int main() {
	A* pA = NULL;  // 错误
	
	pA->Print1();
	pA->Print2();
	pA->Print3();
	
	return 0;
}



//
g++ 222.cpp -std=c++11

txdy827@gpulab-k40:~/Desktop$ ./a.out 

Segmentation fault (core dumped)


3、列表初始化

#include<iostream>
#include<vector>
using namespace std;
class A {
private:
	int n1;
	int n2;
public:
	//A():n2(0),n1(n2+2){ }     // n1 is -858993458    n2 is 0
	A() :n1(0), n2(n1 + 2) { }  // n1 is 0    n2 is 2  ,按顺序可以使用,但是一般都会出问题。
	void Print1() {
		cout << "n1 is " << n1 << "    n2 is " << n2 << endl;
	}	
};
int main() {
	A  a;	
	a.Print1();	
	return 0;
}

4、sizeof c语言中的

#include<string.h>
#include<stdio.h>
int SizeOf(char pString[]){
        return sizeof(pString);
}

int main() {
        char * pString1 = "BONC_TEST";
        int c = sizeof('c');
        printf("sizeof(c) is %d\n",c);
        int size1 = sizeof(pString1);
        int size2 = sizeof(*pString1);
        char pString2[100] = "BONC_TEST";
        int pString3[100] = {100};
        int size3 = sizeof(pString3);  // 400 = 100 X 4
        int size5 = sizeof(pString2);  // 100 = 100 X 1
        int size4 = SizeOf(pString2);
        printf("%d,%d,%d,%d,%d\n", size1, size2, size3, size4,size5);

                return 0;
}

// 输出,
sizeof(c) is 4
8,1,400,8
如果sizeof()后面加数组,那就直接相乘,数组个数 X 数组元素所占字节

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值