1. 程式人生 > >C++類和繼承中的部分經典面試題

C++類和繼承中的部分經典面試題

1.如何實現一個無法繼承的類?

思路:

私有繼承不可見,建構函式是合成的

class A
{
public:
	static A* GetObj1()    //靜態成員函式
	{
		return new A;   //new 物件
	}
	static A GetObj2()
	{
		return A(); //使用匿名物件拷貝構造
	}
private:
	A()
	{}
	int _a;
};


class B :public A
{
private:
	int _b;
};

int main()
{
	A *p1 = A::GetObj1();
	A a1 = A::GetObj2();
	B b;

	system("pause");
	return 0;
}

2.實現一個類定義出的物件在堆上

思路:

防拷貝的條件: 1)宣告成私有的 ,只宣告不實現 2)將拷貝構造、建構函式、賦值運算子過載宣告為私有的
class A
{
public:
	static A* GetObj1()//靜態成員函式
	{
		return new A;//new物件
	}
	static A GetObj2()
	{
		return A();//使用匿名物件拷貝構造
	}
private:
	A()
	{}
	A(const A& a);
	A& operator=(const A&a);
	int _a;

};
int main()
{
	A *p1 = A::GetObj1();//在堆上
	A a1(*p1);//棧上
	A a2 = *p1; //棧上
	system("pause");
	return 0;
}

3.實現以個類定義出的物件在棧上

思路和上面的一樣

class A
{
public:

	static A& GetObj2()
	{
		return  A();//使用匿名物件拷貝構造
	}
private:
	A()
	{}

	int _a;

};

int main()
{
	A a = A::GetObj2();

	system("pause");
	return 0;
}