01_c++虚方法、抽象函数、动态数组、命名空间

#include<iostream>
#include<string>

class first_class
{
public:
	first_class();
	~first_class();
	virtual void say_hello(); //前方加virtual为虚方法声明
	static int getCount();

protected:
	int count = 0;

private:
	friend class third_class;
	static int test_count;
	
};

class second_class : public first_class
{
public:
	second_class();
	~second_class();
	void say_hello();
};

class third_class
{
public:
	void printf_count(first_class * the_class);
};

int first_class::test_count = 0;

first_class::first_class()
{
	std::cout << "the first class open \n" ;

	test_count++;

}

first_class::~first_class()
{
	std::cout << "the first class close \n";
}

void first_class::say_hello()
{
	std::cout << "hello c++. \n" ;
}

int first_class::getCount()
{
	return test_count;
}

second_class::second_class()
{
	std::cout << "the second class open \n";
}

second_class::~second_class()
{
	std::cout << "the second class close \n";
}

void second_class::say_hello()
{
	std::cout << "the sencond hello \n";
}

void third_class::printf_count(first_class * the_class)
{
	std::cout << "the count is " << the_class->test_count << "\n";
}

int main()
{
	first_class class_1;
	second_class class_2;
	third_class class_3;

	first_class* test_class = new second_class();

	class_1.say_hello();
	class_2.say_hello();
	test_class->say_hello();

	std::cout << first_class::getCount() << "\n";

	class_3.printf_count(&class_1);

	system("pause");
	return 0;
}
first_class* test_class = new second_class();
test_class->say_hello();

这样定义并引用方法时, 不使用虚方法会直接引用父类的方法。

virtual void say_hello() = 0;

声明抽象函数, 表示这个函数在这个类中没有定义。

std::cin >> i;
int * x = new int[i];
x[0]...........

动态数组

副本构造器防止在类与类之间相互赋值时, 中间有指针变量, 用副本构造器可以使其不仅只复制地址。

#include <iostream>
using namespace std;
 
// 第一个命名空间
namespace first_space{
   void func(){
      cout << "Inside first_space" << endl;
   }
}
// 第二个命名空间
namespace second_space{
   void func(){
      cout << "Inside second_space" << endl;
   }
}
int main ()
{
 
   // 调用第一个命名空间中的函数
   first_space::func();
   
   // 调用第二个命名空间中的函数
   second_space::func(); 
 
   return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值