#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;
}